从MongoDB中仅选择一个字段?
您可以使用$and运算符。首先让我们创建一个包含文档的集合-
>db.selectingASingleFieldDemo.insertOne({"StudentFirstName":"John","StudentAge":23,"StudentCountryName":"US"}); { "acknowledged" : true, "insertedId" : ObjectId("5cd547142cba06f46efe9f02") } >db.selectingASingleFieldDemo.insertOne({"StudentFirstName":"Carol","StudentAge":21,"StudentCountryName":"UK"}); { "acknowledged" : true, "insertedId" : ObjectId("5cd5471f2cba06f46efe9f03") } >db.selectingASingleFieldDemo.insertOne({"StudentFirstName":"David","StudentAge":24,"StudentCountryName":"AUS"}); { "acknowledged" : true, "insertedId" : ObjectId("5cd5472c2cba06f46efe9f04") } >db.selectingASingleFieldDemo.insertOne({"StudentFirstName":"Robert","StudentAge":26,"StudentCountryName":"AUS"}); { "acknowledged" : true, "insertedId" : ObjectId("5cd548382cba06f46efe9f05") }
以下是在find()
方法的帮助下显示集合中所有文档的查询-
> db.selectingASingleFieldDemo.find().pretty();
这将产生以下输出-
{ "_id" : ObjectId("5cd547142cba06f46efe9f02"), "StudentFirstName" : "John", "StudentAge" : 23, "StudentCountryName" : "US" } { "_id" : ObjectId("5cd5471f2cba06f46efe9f03"), "StudentFirstName" : "Carol", "StudentAge" : 21, "StudentCountryName" : "UK" } { "_id" : ObjectId("5cd5472c2cba06f46efe9f04"), "StudentFirstName" : "David", "StudentAge" : 24, "StudentCountryName" : "AUS" } { "_id" : ObjectId("5cd548382cba06f46efe9f05"), "StudentFirstName" : "Robert", "StudentAge" : 26, "StudentCountryName" : "AUS" }
以下是从MongoDB中仅选择单个字段的查询-
> db.selectingASingleFieldDemo.find( ... { $and:[{StudentAge: { $gt:21 } }, ... {"StudentCountryName" : "AUS"}] }, ... {StudentFirstName: 1, _id: 0});
这将产生以下输出-
{ "StudentFirstName" : "David" } { "StudentFirstName" : "Robert" }