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 Answer 1

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.

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

2 Comments

Yes, It works. Is there any way to just return matching objects rather than entire document?
@ArunBabuVijayanath modified my answer

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.