仅从 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" }
广告