首先让我们创建一个包含文档的集合-
> db.findOneWorkingDemo.insertOne({"ClientId":1,"ClientName":"Larry","ClientAge":26}); { "acknowledged" : true, "insertedId" : ObjectId("5cd7c1716d78f205348bc64d") } > db.findOneWorkingDemo.insertOne({"ClientId":2,"ClientName":"Chris","ClientAge":28}); { "acknowledged" : true, "insertedId" : ObjectId("5cd7c17d6d78f205348bc64e") } > db.findOneWorkingDemo.insertOne({"ClientId":3,"ClientName":"Robert","ClientAge":34}); { "acknowledged" : true, "insertedId" : ObjectId("5cd7c1896d78f205348bc64f") }
以下是在find()
方法的帮助下显示集合中所有文档的查询-
> db.findOneWorkingDemo.find().pretty();
这将产生以下输出-
{ "_id" : ObjectId("5cd7c1716d78f205348bc64d"), "ClientId" : 1, "ClientName" : "Larry", "ClientAge" : 26 } { "_id" : ObjectId("5cd7c17d6d78f205348bc64e"), "ClientId" : 2, "ClientName" : "Chris", "ClientAge" : 28 } { "_id" : ObjectId("5cd7c1896d78f205348bc64f"), "ClientId" : 3, "ClientName" : "Robert", "ClientAge" : 34 }
以下是要findOne()
使用ObjectId实现的查询-
> db.findOneWorkingDemo.findOne({"_id":ObjectId("5cd7c17d6d78f205348bc64e")});
这将产生以下输出-
{ "_id" : ObjectId("5cd7c17d6d78f205348bc64e"), "ClientId" : 2, "ClientName" : "Chris", "ClientAge" : 28 }