要选择MongoDB中的特定子文档,请使用find()
。让我们创建一个包含文档的集合-
> db.demo37.insertOne({"Details":[{"Name":"Chris","Age":21},{"Name":"David","Age":23}]}); { "acknowledged" : true, "insertedId" : ObjectId("5e176635cfb11e5c34d898d7") } > db.demo37.insertOne({"Details":[{"Name":"Sam","Age":23},{"Name":"Robert","Age":25}]}); { "acknowledged" : true, "insertedId" : ObjectId("5e17664acfb11e5c34d898d8") }
在find()
方法的帮助下显示集合中的所有文档-
> db.demo37.find();
这将产生以下输出-
{ "_id" : ObjectId("5e176635cfb11e5c34d898d7"), "Details" : [ { "Name" : "Chris", "Age" : 21 }, { "Name" : "David", "Age" : 23 } ] } { "_id" : ObjectId("5e17664acfb11e5c34d898d8"), "Details" : [ { "Name" : "Sam", "Age" : 23 }, { "Name" : "Robert", "Age" : 25 } ] }
以下是选择子文档的查询-
> db.demo37.find({'Details.Name' : 'Sam'},{_id: 0, 'Details.$.Name': 1});
这将产生以下输出-
{ "Details" : [ { "Name" : "Sam", "Age" : 23 } ] }