FedeLanza
FedeLanza

Reputation: 183

Querying an entire specific array inside another array in mongoDB

I have a mongoDB collection, called myCollection, and inside myCollection there is a structure like this:

{
    "id": 1234,
    "posts": [
       [
          {
             "id": "0.0",
             "name": "john",
             "message": "hello"
          },
          {
             "id": "0.1",
             "name": "jane",
             "message": "good morning"
          },
          {
             "id": "0.2",
             "name": "josh",
             "message": "good evening"
          }
       ],
       [
          {
             "id": "1.0",
             "name": "mark",
             "message": "good lunch"
          }
       ],
       [
          {
             "id": "2.0",
             "name": "john",
             "message": "bye bye"
          },
          {
             "id": "2.1",
             "name": "mark",
             "message": "hi"
          }
       ]
    ]
}

Can anyone tell me how I can query this structure to obtain the ENTIRE array that contains a specific object? For example, launching a query around this specific object:

{
    "id": "2.0",
    "name": "john",
    "message": "bye bye"
}

I would to obtain this entire array:

       [
          {
             "id": "2.0",
             "name": "john",
             "message": "bye bye"
          },
          {
             "id": "2.1",
             "name": "mark",
             "message": "hi"
          }
       ]

Upvotes: 0

Views: 1892

Answers (1)

the_mahasagar
the_mahasagar

Reputation: 1201

Hope below query is help :

db.myCollection.aggregate([
  { $match : { "id": 1234}},
  { $unwind  : '$posts'},
  {$match : {
        'posts' : { $elemMatch : { 'id' : '2.0',name : 'john'}} 
     }
  },
  { $unwind : '$posts'},
  { $project : {
      'id' : '$posts.id',
      name : '$posts.name',
      message :'$posts.message',
      _id : 0
     }
  }
])

Upvotes: 1

Related Questions