对于MongoDB中的子数组文档,请使用聚合和$sort。首先让我们创建一个包含文档的集合-
> db.demo23.insertOne(
...{
...
... "StudentDetails" : [{
... "Name" : "David",
... "Age" : 23,
...
... }, {
... "Name" : "Adam",
... "Age" : 24,
... }]
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5e14c3eb22d07d3b95082e71")
}在find()方法的帮助下显示集合中的所有文档-
> db.demo23.find().pretty()
这将产生以下输出-
{
"_id" : ObjectId("5e14c3eb22d07d3b95082e71"),
"StudentDetails" : [
{
"Name" : "David",
"Age" : 23
},
{
"Name" : "Adam",
"Age" : 24
}
]
}这是与$sort一起用于子数组文档的查询-
> db.demo23.aggregate([
... { "$unwind" : "$StudentDetails"} ,
... { "$sort" : { "StudentDetails.Name" : 1}},
... { "$match" : { }} ,
... { "$group" : { "StudentDetails" : { "$push" : { "Name" : "$StudentDetails.Name"}} , "_id" : null}} ,
... { "$project" : { "_id" : 0 , "StudentDetails" : 1}}
... ]);这将产生以下输出-
{ "StudentDetails" : [ { "Name" : "Adam" }, { "Name" : "David" } ] }