要查询数组的最后一个对象,请使用aggregate()
。让我们创建一个包含文档的集合-
> db.demo103.insertOne( { "Details" : [ { "StudentId" : 101, "Details" : "MongoDB" }, {"StudentId" : 102, "Details" : "MySQL" }, { "StudentId" : 103, "Details" : "Java" } ], "Details1" : [ { "StudentId" : 104, "Number" : 3 } ] } ); { "acknowledged" : true, "insertedId" : ObjectId("5e2ed2dd9fd5fd66da21446e") }
在find()
方法的帮助下显示集合中的所有文档-
> db.demo103.find();
这将产生以下输出-
{ "_id" : ObjectId("5e2ed2dd9fd5fd66da21446e"), "Details" : [ { "StudentId" : 101, "Details" : "MongoDB" }, { "StudentId" : 102, "Details" : "MySQL" }, { "StudentId" : 103, "Details" : "Java" } ], "Details1" : [ { "StudentId" : 104, "Number" : 3 } ] }
这是查询数组最后一个对象的方法-
> db.demo103.aggregate([ { $project: { Details1: 1, Details: {$arrayElemAt: ["$Details", -1]} } }, { $match: {"Details.StudentId": 103} } ])
这将产生以下输出-
{ "_id" : ObjectId("5e2ed2dd9fd5fd66da21446e"), "Details1" : [ { "StudentId" : 104, "Number" : 3 } ], "Details" : { "StudentId" : 103, "Details" : "Java" } }