在 MongoDB 中对数组进行排序的最简单方法
在 MongoDB 中对数组进行排序的最简单方法是使用 $sort。让我们创建一个包含文档的集合 -
> db.demo242.insertOne(
...
... {"details2":
... [
... {"ShipingDate":new ISODate("2019-10-11"),"Price":1400},
... {"ShipingDate":new ISODate("2019-10-01"),"Price":1600 }
... ]
... }
...
...);
{
"acknowledged" : true,
"insertedId" : ObjectId("5e4429229af932883c61ea44")
}使用 find() 方法从集合中显示所有文档 -
> db.demo242.find();
将生成以下输出 -
{
"_id" : ObjectId("5e4429229af932883c61ea44"), "details2" : [
{ "ShipingDate" : ISODate("2019-10-11T00:00:00Z"), "Price" : 1400 },
{ "ShipingDate" : ISODate("2019-10-01T00:00:00Z"), "Price" : 1600 }
]
}下面是 MongoDB 中对数组进行排序的查询 -
> db.demo242.aggregate([ {$unwind: "$details2"}, {$sort: {"details2.ShipingDate":1}}, {$group: {_id:"$_id", details2: {$push:"$details2.ShipingDate"}}} ]);将生成以下输出 -
{ "_id" : ObjectId("5e4429229af932883c61ea44"), "details2" : [ ISODate("2019-10-01T00:00:00Z"), ISODate("2019-10-11T00:00:00Z") ] }
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP