0

Here is the document

{
  '_id': ObjectId('61a4262a53ddaa8b93374613'),
  'userid': 'renyi',
  'data1': [{'a': 1}, 1, 2, 3],
  'data2': [{'c': 1}, {'b': 2}, {'c': 3}, {'c': 2}],
  'data': {'0': {'a': 1}}
}

With this

coll.find_one({'userid':'renyi','data2.c':1},{'_id':0,"data2.$":1})

I can get

{'data2': [{'c': 1}]}

But how to get

{'data2': [{'c': 1},{'c': 2}]}

1 Answer 1

1

You can use $filter to filter the element within the array in projection.

db.collection.find({
  "userid": "renyi",
  "data2.c": {
    $in: [
      1,
      2
    ]
  }
},
{
  "_id": 0,
  "data2": {
    $filter: {
      input: "$data2",
      cond: {
        $in: [
          "$$this.c",
          [
            1,
            2
          ]
        ]
      }
    }
  }
})

Sample Mongo Playground

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.