在MongoDB中查找当前和以前的文档
要获取当前和以前的文档,请使用sort()
。由于我们只需要2个文档,因此请使用LIMIT(2)。
让我们创建一个包含文档的集合-
> db.demo360.insertOne({id:101,"Name":"Chris"}); { "acknowledged" : true, "insertedId" : ObjectId("5e56a10c54a481fef8ec7a15") } > db.demo360.insertOne({id:102,"Name":"David"}); { "acknowledged" : true, "insertedId" : ObjectId("5e56a11254a481fef8ec7a16") } > db.demo360.insertOne({id:103,"Name":"Bob"}); { "acknowledged" : true, "insertedId" : ObjectId("5e56a11a54a481fef8ec7a17") } > db.demo360.insertOne({id:104,"Name":"Mike"}); { "acknowledged" : true, "insertedId" : ObjectId("5e56a11f54a481fef8ec7a18") }
在find()
方法的帮助下显示集合中的所有文档-
> db.demo360.find();
这将产生以下输出-
{ "_id" : ObjectId("5e56a10c54a481fef8ec7a15"), "id" : 101, "Name" : "Chris" } { "_id" : ObjectId("5e56a11254a481fef8ec7a16"), "id" : 102, "Name" : "David" } { "_id" : ObjectId("5e56a11a54a481fef8ec7a17"), "id" : 103, "Name" : "Bob" } { "_id" : ObjectId("5e56a11f54a481fef8ec7a18"), "id" : 104, "Name" : "Mike" }
以下是在MongoDB中查找当前和先前文档的查询-
> db.demo360.find({ id: { $lte: 102 } }, {id:1, Name: 1 }).sort({_id: -1}).limit(2);
这将产生以下输出-
{ "_id" : ObjectId("5e56a11254a481fef8ec7a16"), "id" : 102, "Name" : "David" } { "_id" : ObjectId("5e56a10c54a481fef8ec7a15"), "id" : 101, "Name" : "Chris" }