要仅获得单个结果,请findOne()
在id的基础上使用和提取。让我们创建一个包含文档的集合-
> db.demo340.insertOne({_id:1,"Name":"Chris",Age:21}); { "acknowledged" : true, "insertedId" : 1 } > db.demo340.insertOne({_id:2,"Name":"David",Age:23}); { "acknowledged" : true, "insertedId" : 2 } > db.demo340.insertOne({_id:3,"Name":"Bob",Age:20}); { "acknowledged" : true, "insertedId" : 3 } > db.demo340.insertOne({_id:4,"Name":"Sam",Age:19}); { "acknowledged" : true, "insertedId" : 4 }
在find()
方法的帮助下显示集合中的所有文档-
> db.demo340.find();
这将产生以下输出-
{ "_id" : 1, "Name" : "Chris", "Age" : 21 } { "_id" : 2, "Name" : "David", "Age" : 23 } { "_id" : 3, "Name" : "Bob", "Age" : 20 } { "_id" : 4, "Name" : "Sam", "Age" : 19 }
这是findby id的查询-
> db.demo340.findOne({_id:1});
这将产生以下输出-
{ "_id" : 1, "Name" : "Chris", "Age" : 21 }