0
{
  "data": {
    "category": "mobile",
    "products": [
      {
        "title": "Redmi Note 10 Pro"
      },
      {
        "title": "Redmi Note 100 Profile"
      }
    ]
  },
  "user": {
    "name": "username"
  }
}

How to get only specific object. Mongodb

I just want object who have the category as "mobile" and title as "Redmi Note 100 Profile"

Result expected:

{
  "data": {
    "category": "mobile",
    "products":{
        "title": "Redmi Note 100 Profile"
      }
  },
  "user": {
    "name": "username"
  }
}

I just don't want this object

{
 "title": "Redmi Note 10 Pro"
}

I'm using this to get

db.collection("products").aggregate([{
              "$unwind": "$data"
            },
              {
                "$match": {
                  "data.category": "mobile",
                  "data.products.title": "Redmi Note 100 Profile",
                }
              }])
            .toArray();

But, it's give me 2 object ?

{
  "data": {
    "category": "mobile",
    "products": [
      {
        "title": "Redmi Note 10 Pro"
      },
      {
        "title": "Redmi Note 100 Profile"
      }
    ]
  },
  "user": {
    "name": "username"
  }
}

How to do ?

1 Answer 1

1

You can use aggregate framework with $unwind to unwind the products array and $match to filter out

Working playground

db.collection.aggregate([
  {
    "$unwind": "$data.products"
  },
  {
    "$match": {
      "data.products.title": "Smartphone 1000 Pro Max Ultra Mega"
    }
  }
])
Sign up to request clarification or add additional context in comments.

7 Comments

i have update my code as you answer. But it's work for some field, but sometimes it's not work. So i have edited my question with my new problem, please check yourself and solve my problem.
You cannot "$unwind": "$data" as data is not an array. You need to do this "$unwind": "$data.products"
It's worked but, it's not giving the "user" & "data" object as i mentioned.
ok, yoou want like this "products": [? I mean products in array, that's the only difference?
Yeah, it's worked.. that's my fault, i was created some function that is why...
|

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.