1

I have an mongoDB objetc like :

[
  {
    "items": [
      {
        "title": "hello",
        "options": [
          {
            "value": "A",
            "image": "img1",
            "des": "des1"
          },
          {
            "value": "B",
            "image": "img2",
            "des": "des2"
          },
          
        ]
      }
    ]
  }
]

When I retrieve data from the collection, I want to retrieve only value key from the options of the items array.

Output should look like :

{
 "items":[
  {
     "options" :[
       {  "value" :"A" },
       {  "value" :"B" },
   ]
  }
 ]
}

How can i do this?

6
  • use projection { "items.options.value": 1 } see more about projection. Commented Jun 5, 2021 at 7:40
  • turivishal If you specify the query it would be helpful for me. Thanks Commented Jun 5, 2021 at 7:48
  • it is same you can use projection as per my comment, if you want to use aggregation then see $project Commented Jun 5, 2021 at 7:48
  • if you see the attached links in comment, its easy to use, just follow the instructions as per documentation. it is not hard to understand I think you just have to use { "items.options.value": 1 } projection simple. Commented Jun 5, 2021 at 7:50
  • Ok, I am trying Commented Jun 5, 2021 at 7:53

1 Answer 1

1

You can do it like this:

db.collection.find({}, { "items.options.value": 1})

Here is the working example: https://mongoplayground.net/p/FqDaQ7Q-y-Y

Or you can do it like this:

db.collection.aggregate([
  {
    "$project": {
      "items.options.value": 1
    }
  }
])

Here is the working example: https://mongoplayground.net/p/jPFYtXYBvpI

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

Comments

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.