MongoDB 查询从文档中仅选择并显示某个特定的字段?
让我们先创建一个包含文档的集合 -
> 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" }
广告