首先让我们创建一个包含文档的集合-
> db.querySelectDemo.insertOne({UserId:100,UserName:"Chris",UserAge:25}); { "acknowledged" : true, "insertedId" : ObjectId("5ce90eb478f00858fb12e90e") } > db.querySelectDemo.insertOne({UserId:101,UserName:"Robert",UserAge:26}); { "acknowledged" : true, "insertedId" : ObjectId("5ce90ec578f00858fb12e90f") } > db.querySelectDemo.insertOne({UserId:103,UserName:"David",UserAge:27}); { "acknowledged" : true, "insertedId" : ObjectId("5ce90ed478f00858fb12e910") }
以下是在find()
方法的帮助下显示集合中所有文档的查询-
> db.querySelectDemo.find().pretty();
这将产生以下输出-
{ "_id" : ObjectId("5ce90eb478f00858fb12e90e"), "UserId" : 100, "UserName" : "Chris", "UserAge" : 25 } { "_id" : ObjectId("5ce90ec578f00858fb12e90f"), "UserId" : 101, "UserName" : "Robert", "UserAge" : 26 } { "_id" : ObjectId("5ce90ed478f00858fb12e910"), "UserId" : 103, "UserName" : "David", "UserAge" : 27 }
以下是通过在find()
−中将其设置为TRUE来仅包含特定字段的查询
> db.querySelectDemo.find({},{_id:0,UserName:true});
这将产生以下输出-
{ "UserName" : "Chris" } { "UserName" : "Robert" } { "UserName" : "David" }