1

I have bunch of documents in the following format in my mongodb, I am using moongoose as ORM.

Can some one help me make a query to get all the contents having the name=abc inside data-items.content

Document 1:

{
 "title": "Some title",
 "addresse": "data",
 "data-items": { 
 "content": [
   {
   "name": "abc",
   "age": "poster5.jpg"
   },
   {
    "name": "def",
    "age": "poster5.jpg"
   },
   {
    "name": "hij",
    "age": "poster5.jpg"
   }]
 }
}

Document 2:

{
"title": "another title",
"addresse": "data",
"data-items": {
  "content": [
    {
      "name": "abc",
      "age": "poster7.jpg"
    },
    {
      "name": "def",
      "age": "poster5.jpg"
    },
    {
      "name": "hij",
      "age": "poster5.jpg"
    }]
  }
 }

Any help is appreciated

1 Answers1

1

You can simply use the dot notation to query an array of nested documents:

Model.find({"data-items.content.name": "abc"})

EDIT: to get only subdocuments matching your condition you can use below aggregation:

Model.aggregate([
    {
        $match: {
            "data-items.content.name": "abc"
        }
    },
    {
        $unwind: "$data-items.content"
    },
    {
        $match: {
            "data-items.content.name": "abc"
        }
    },
    {
        $replaceRoot: {
            newRoot: "$data-items.content"
        }
    }
])

$unwind will give you single document per content and $replaceRoot will promote it to the root level.

mickl
  • 48,568
  • 9
  • 60
  • 89