如何在所有MongoDB文档中查找数组中的最新条目?
要在所有文档中查找数组中的最新条目,请使用aggregate()。让我们创建一个包含文档的集合-
> db.demo179.insertOne( ...{ ... "Name":"Chris", ... "Details": [ ... { ... "Id":101, ... "Subject":"MongoDB" ... }, ... { ... "Id":102, ... "Subject":"MySQL" ... } ... ] ...} ...); { "acknowledged" : true, "insertedId" : ObjectId("5e3980299e4f06af551997f9") } > db.demo179.insertOne( ...{ ... "Name":"David", ... "Details": [ ... { ... "Id":103, ... "Subject":"Java" ... }, ... { ... "Id":104, ... "Subject":"C" ... } ... ] ...} ...); { "acknowledged" : true, "insertedId" : ObjectId("5e39802a9e4f06af551997fa") }
在find()方法的帮助下显示集合中的所有文档-
> db.demo179.find().pretty();
这将产生以下输出-
{ "_id" : ObjectId("5e3980299e4f06af551997f9"), "Name" : "Chris", "Details" : [ { "Id" : 101, "Subject" : "MongoDB" }, { "Id" : 102, "Subject" : "MySQL" } ] } { "_id" : ObjectId("5e39802a9e4f06af551997fa"), "Name" : "David", "Details" : [ { "Id" : 103, "Subject" : "Java" }, { "Id" : 104, "Subject" : "C" } ] }
以下是在所有文档中查找数组中最新条目的查询-
> db.demo179.aggregate([ ... { "$unwind": "$Details" }, ... { "$sort": { "Details.Id": -1 } }, ... { "$limit": 2 }, ... { ... "$group": { ... "_id": "$Details.Id", ... "Name" : { "$first": "$Name" }, ... "Details": { "$push": "$Details" } ... } ... }, ... { ... "$project": { ... "_id": 0, "Name": 1, "Details": 1 ... } ... } ...])
这将产生以下输出-
{ "Name" : "David", "Details" : [ { "Id" : 103, "Subject" : "Java" } ] } { "Name" : "David", "Details" : [ { "Id" : 104, "Subject" : "C" } ] }