1

I cannot reconstruct this: Retrieve only the queried element in an object array in MongoDB collection.

Remember, there are two id which should match and I want the Image: [] back. This is my structur.

{
  "_id" : ObjectId("5ee4e57a6e5a926bdeb1e406"),
  "Display" : [
    { 
      "_id" : ObjectId("5ee5b7db9245084840dc624f"),
      "Image" : [
      {Document I want},
      {Document I want}]
    }
  ]
}

My best try:

db.User.aggregate([
{"$match" : 
  {"_id": ObjectId("5ee4e57a6e5a926bdeb1e406")}
},{
  "$project" :{
  "Display" : {
  $filter: {
    input: ObjectId("5ee5b7db9245084840dc624f"),
    as: "id",
    cond: {
      "$Display._id": "$$id"}
  }
}
}
}]);

1 Answers1

1

In your aggregation, you are missing $eq operator.

Aggregation approach:

db.collection.aggregate([
  {
    $match: {
      _id: 1
    }
  },
  {
    $project: {
      Display: {
        $filter: {
          input: "$Display",
          as: "d",
          cond: {
            $eq: [
              "$$d._id",
              100
            ]
          }
        }
      }
    }
  }
])

MongoPLayGroundLink

Find approach:

db.collection.find({
  _id: 1,
  "Display._id": 100
},
{
  "Display.$": 1
})

MongoPLayGroundLink

ngShravil.py
  • 4,742
  • 3
  • 18
  • 30