为此,请在MongoDB中使用findOne()。findOne()返回一个满足集合中指定查询条件的文档。
让我们创建一个包含文档的集合-
> db.demo596.insertOne({_id:1,"FirstName":"John","LastName":"Smith"}); { "acknowledged" : true, "insertedId" : 1 } > db.demo596.insertOne({_id:2,"FirstName":"John","LastName":"Doe"}); { "acknowledged" : true, "insertedId" : 2 } > db.demo596.insertOne({_id:3,"FirstName":"Chris","LastName":"Brown"}); { "acknowledged" : true, "insertedId" : 3 } > db.demo596.insertOne({_id:4,"FirstName":"David","LastName":"Miller"}); { "acknowledged" : true, "insertedId" : 4 }
在find()方法的帮助下显示集合中的所有文档-
> db.demo596.find();
这将产生以下输出-
{ "_id" : 1, "FirstName" : "John", "LastName" : "Smith" } { "_id" : 2, "FirstName" : "John", "LastName" : "Doe" } { "_id" : 3, "FirstName" : "Chris", "LastName" : "Brown" } { "_id" : 4, "FirstName" : "David", "LastName" : "Miller" }
这是仅检索单个文档的查询-
> db.demo596.findOne({"FirstName":"John"});
这将产生以下输出-
{ "_id" : 1, "FirstName" : "John", "LastName" : "Smith" }