0

one item in the collection looks as shown below.

{
"_id" : ObjectId("4f7ee46e08403d063ab0b4f9"),
"name" : "MongoDB",
"notes" : [
            {
              "title" : "Hello MongoDB",
              "content" : "Hello MongoDB"
            },
            {
              "title" : "ReplicaSet MongoDB",
              "content" : "ReplicaSet MongoDB"
            }
         ]
}

lets say i want to retrieve all the notes of all documents as a single array, how should i wite my query? give mongoose and or mongoDB example

1 Answer 1

1

You can use aggregation to get the desires result. Use a $unwind stage to flatten the array values into documents. Then, follow by a $group stage to $push all the notes into a single array. Optionally, use a $project stage to output the expected fields.

db.collection.aggregate([
    {"$unwind":"$notes"}, 
    {"$group":{"_id": null, "notes":{"$push":"$notes"}}}, 
    {"$project":{"_id":0, "notes":1}}
]);
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.