1

I have a document similar to this:

{
  "field1": "a",
  "field2": {
    "subfield1": "sa",
    "subfield2": [
      {
        "name": "abc"
      },
      {
        "name": "def"
      }
    ]
  }
}

I want something like this:

{
   "field1":"a",
   "field2":{
      "subfield1":"sa",
      "subfield2":["abc","def"]
   }
}

Thanks in advance!

1

1 Answer 1

2

Using projection into find:

db.collection.find({/*your find query*/},
{
  "field1": 1,
  "field2.subfield1": 1,
  "field2.subfield2": "$field2.subfield2.name"
})

Example here

Using aggregate:

db.collection.aggregate([
  {
    "$project": {
      "field1": 1,
      "field2.subfield1": 1,
      "field2.subfield2": "$field2.subfield2.name"
    }
  }
])

Example here

Also you can add "_id": 0, to not output the _id. Examples here and here

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

3 Comments

But this doesn't give me output like this "subfield2":["abc","def"] instead gives me nested arrays and documents
Oops sorry, I forgot "field2.subfield1": 1,. Now is fixed. The output is the same as desired one: "subfield2":["abc","def"]
Like @sadsun, the first of these doesn't work for me (using db.collection.find with a projection argument) (even though I see it works in your mongoplayground.net link) it only works when I use db.collection.aggregate with a $project stage. I am on MongoDB version 3.6.6. Notice both these other answers use aggregate, here and here

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.