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

Xsmael
  • 3,624
  • 7
  • 44
  • 60

1 Answers1

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}}
]);
4J41
  • 5,005
  • 1
  • 29
  • 41