要返回特定字段,请使用find()
MongoDB中的方法。首先让我们创建一个包含文档的集合-
> db.specificFieldDemo.insertOne({"FirstName":"John","LastName":"Doe"}); { "acknowledged" : true, "insertedId" : ObjectId("5cb8019a623186894665ae31") } > db.specificFieldDemo.insertOne({"FirstName":"John","LastName":"Smith"}); { "acknowledged" : true, "insertedId" : ObjectId("5cb801ab623186894665ae32") } > db.specificFieldDemo.insertOne({"FirstName":"David","LastName":"Miller"}); { "acknowledged" : true, "insertedId" : ObjectId("5cb801b3623186894665ae33") } > db.specificFieldDemo.insertOne({"FirstName":"Sam","LastName":"Williams"}); { "acknowledged" : true, "insertedId" : ObjectId("5cb801bf623186894665ae34") }
以下是在find()
方法的帮助下显示集合中所有文档的查询-
> db.specificFieldDemo.find().pretty();
这将产生以下输出-
{ "_id" : ObjectId("5cb8019a623186894665ae31"), "FirstName" : "John", "LastName" : "Doe" } { "_id" : ObjectId("5cb801ab623186894665ae32"), "FirstName" : "John", "LastName" : "Smith" } { "_id" : ObjectId("5cb801b3623186894665ae33"), "FirstName" : "David", "LastName" : "Miller" } { "_id" : ObjectId("5cb801bf623186894665ae34"), "FirstName" : "Sam", "LastName" : "Williams" }
以下是返回特定字段的查询。在这里,我们返回字段“ LastName”-
> db.specificFieldDemo.find({},{_id:0,LastName:1});
这将产生以下输出-
{ "LastName" : "Doe" } { "LastName" : "Smith" } { "LastName" : "Miller" } { "LastName" : "Williams" }