如何从MongoDB集合中获取数组?
您可以使用聚合框架。首先让我们创建一个包含文档的集合-
> db.getArrayDemo.insertOne( { "CustomerId":101, "CustomerDetails":[ { "CustomerName":"Larry", "CustomerFriendDetails":[ { "CustomerFriendName":"Sam" }, { "CustomerFriendName":"Robert" } ] }, { "CustomerName":"Chris", "CustomerFriendDetails":[ { "CustomerFriendName":"David" }, { "CustomerFriendName":"Carol" } ] } ] } ); { "acknowledged" : true, "insertedId" : ObjectId("5cda4949b50a6c6dd317adb7") }
以下是在find()
方法的帮助下显示集合中所有文档的查询-
> db.getArrayDemo.find().pretty();
这将产生以下输出-
{ "_id" : ObjectId("5cda4949b50a6c6dd317adb7"), "CustomerId" : 101, "CustomerDetails" : [ { "CustomerName" : "Larry", "CustomerFriendDetails" : [ { "CustomerFriendName" : "Sam" }, { "CustomerFriendName" : "Robert" } ] }, { "CustomerName" : "Chris", "CustomerFriendDetails" : [ { "CustomerFriendName" : "David" }, { "CustomerFriendName" : "Carol" } ] } ] }
以下是从MongoDB集合中获取数组的查询-
> db.getArrayDemo.aggregate([ { "$unwind": "$CustomerDetails" }, { "$unwind": "$CustomerDetails.CustomerFriendDetails"}, { "$group": { "_id": null, "CustomerFriendDetails": { "$push": "$CustomerDetails.CustomerFriendDetails.CustomerFriendName" } } } ]);
这将产生以下输出-
{ "_id" : null, "CustomerFriendDetails" : [ "Sam", "Robert", "David", "Carol" ] }