如何使用 MongoDB shell 从文档中获取具有特定值的数据项?
要获取具有特定值的项,只需使用 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 }
广告