MongoDB查询排序嵌套数组?
要在MongoDB中对嵌套数组进行排序,请使用$sort。让我们创建一个包含文档的集合-
> db.demo505.insertOne(
... {
... "details": [
... {
... Name:"Chris",
... "Score":58
... }, {
...
... Name:"Bob",
... "Score":45
... }, {
...
... Name:"John",
... "Score":68
... }, {
...
... Name:"David",
... "Score":46
... }
... ]
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5e882a6b987b6e0e9d18f574")
}在find()方法的帮助下显示集合中的所有文档-
> db.demo505.find();
这将产生以下输出-
{ "_id" : ObjectId("5e882a6b987b6e0e9d18f574"), "details" : [
{ "Name" : "Chris", "Score" : 58 },
{ "Name" : "Bob", "Score" : 45 },
{ "Name" : "John", "Score" : 68 },
{ "Name" : "David", "Score" : 46 }
] }以下是对嵌套数组进行排序的查询-
> db.demo505.aggregate([
... { $unwind: "$details" },
... { $sort: { "details.Score": 1 } },
... { $group: { _id: "$_id", details: { $push: "$details" } } }
... ]);这将产生以下输出-
{ "_id" : ObjectId("5e882a6b987b6e0e9d18f574"), "details" : [
{ "Name" : "Bob", "Score" : 45 },
{ "Name" : "David", "Score" : 46 },
{ "Name" : "Chris", "Score" : 58 },
{ "Name" : "John", "Score" : 68 }
] }热门推荐
10 祝女儿简短祝福语大全
11 大学新年祝福语简短创意
12 元旦适合的祝福语简短
13 朋友出远门祝福语简短
14 初六简短的祝福语
15 祝男孩生日祝福语简短
16 同事调离的祝福语简短
17 拜年红包的祝福语简短
18 妈妈生日祝福语简短励志