Home » Javascript » Find specific array, deep in a nested Mongo collection

Find specific array, deep in a nested Mongo collection

Posted by: admin November 1, 2017 Leave a comment

Questions:

I have a nested Mongo collection which looks like the following:

{
  "_id": "BaiD76JR3gZFPKchn",
  "ownerAdmin": "NsgdNHh84XrBJALAK",
  "activities": [
    {
      "id": "a1",
      "email": "[email protected]",
      "type": "image",
      "description": "Another one",
      "createdAt": "2017-10-25T21:39:44.769Z",
      "pins":
      "action": "https://www.dropbox.com/as"
    },
    {
      "id": "a2",
      "email": "[email protected]",
      "type": "image",
      "description": "Comment This image For me",
      "createdAt": "2017-10-25T18:42:00.484Z",
      "action": "https://www.dropbox.com/s/bty2ds"
    },
    {
      "id": "a3"
      "email": "[email protected]",
      "type": "progress",
      "description": "dasd",
      "createdAt": "2017-10-24T17:28:11.748Z",
      "action": 50
    }
  ],
  "createdAt": "2017-10-24T17:27:54.828Z"
}

I’m trying to query using Collection.findOne("BaiD76JR3gZFPKchn",), to return an object in “activities” using 2 field “id:a2” AND “type:image”, so I end up with :

{
  "id": "a2",
  "email": "[email protected]",
  "type": "image",
  "description": "Comment This image For me",
  "createdAt": "2017-10-25T18:42:00.484Z",
  "action": "https://www.dropbox.com/s/bty2ds"
}
Answers:

Try adding projection into your query.

db.collection.findOne( { _id: "BaiD76JR3gZFPKchn" },
               { activities: { $elemMatch: { id: "a2",type:"image"} }, _id: 0 })