以数组形式仅返回特定字段(电话号码)的 MongoDB 查询?
让我们用文档创建一个集合 −
> db.demo166.insertOne({"details" : { "UserName" : "Chris", "UserAge":29, "PhoneDetails" : { "PhoneNumber" : "98646463533" } } }); { "acknowledged" : true, "insertedId" : ObjectId("5e368b159e4f06af551997cf") } > db.demo166.insertOne({"details" : { "UserName" : "David", "UserAge":21, "PhoneDetails" : { "PhoneNumber" : "87664534654" } } }); { "acknowledged" : true, "insertedId" : ObjectId("5e368b159e4f06af551997d0") }
使用 find() 方法从集合中显示所有文档 −
> db.demo166.find();
这将产生以下输出 −
{ "_id" : ObjectId("5e368b159e4f06af551997cf"), "details" : { "UserName" : "Chris", "UserAge" : 29, "PhoneDetails" : { "PhoneNumber" : "98646463533" } } } { "_id" : ObjectId("5e368b159e4f06af551997d0"), "details" : { "UserName" : "David", "UserAge" : 21, "PhoneDetails" : { "PhoneNumber" : "87664534654" } } }
以下查询将仅以数组形式返回特定字段(电话号码) −
> db.demo166.distinct("details.PhoneDetails.PhoneNumber");
这将产生以下输出 −
[ "98646463533", "87664534654" ]
广告