要获取具有特定值的项目,只需使用find()
。让我们创建一个包含文档的集合-
> db.demo563.insertOne({"Name":"Chris","Age":21,"isMarried":true}){ "acknowledged" : true, "insertedId" : ObjectId("5e8f546c54b4472ed3e8e878") } > db.demo563.insertOne({"Name":"Bob","Age":23,"isMarried":false}){ "acknowledged" : true, "insertedId" : ObjectId("5e8f547854b4472ed3e8e879") } > db.demo563.insertOne({"Name":"Carol","Age":23,"isMarried":true}){ "acknowledged" : true, "insertedId" : ObjectId("5e8f548b54b4472ed3e8e87a") } > db.demo563.insertOne({"Name":"Mike","Age":21,"isMarried":true}){ "acknowledged" : true, "insertedId" : ObjectId("5e8f549454b4472ed3e8e87b") }
在find()
方法的帮助下显示集合中的所有文档-
> db.demo563.find();
这将产生以下输出-
{ "_id" : ObjectId("5e8f546c54b4472ed3e8e878"), "Name" : "Chris", "Age" : 21, "isMarried" : true } { "_id" : ObjectId("5e8f547854b4472ed3e8e879"), "Name" : "Bob", "Age" : 23, "isMarried" : false } { "_id" : ObjectId("5e8f548b54b4472ed3e8e87a"), "Name" : "Carol", "Age" : 23, "isMarried" : true } { "_id" : ObjectId("5e8f549454b4472ed3e8e87b"), "Name" : "Mike", "Age" : 21, "isMarried" : true }
以下是使用MongoDB Shell从文档中获取项目的查询
> db.demo563.find({Age:21},{isMarried:true,Name:1,Age:1});
这将产生以下输出-
{ "_id" : ObjectId("5e8f546c54b4472ed3e8e878"), "Name" : "Chris", "Age" : 21, "isMarried" : true } { "_id" : ObjectId("5e8f549454b4472ed3e8e87b"), "Name" : "Mike", "Age" : 21, "isMarried" : true }