让我们创建一个包含文档的集合-
> db.demo345.insertOne({ ... "UserName" : "Robert", ... "UserDetails" : [ ... { ... "isMarried" : false, ... "CountryName":"US" ... ... }, ... { ... "isMarried" : true, ... "CountryName":"UK" ... ... }, ... { ... "isMarried" : false, ... "CountryName":"AUS" ... ... } ... ] ... } ... ) { "acknowledged" : true, "insertedId" : ObjectId("5e5404fdf8647eb59e5620ac") }
在find()
方法的帮助下显示集合中的所有文档-
> db.demo345.find();
这将产生以下输出-
{ "_id" : ObjectId("5e5404fdf8647eb59e5620ac"), "UserName" : "Robert", "UserDetails" : [ { "isMarried" : false, "CountryName" : "US" }, { "isMarried" : true, "CountryName" : "UK" }, { "isMarried" : false, "CountryName" : "AUS" } ] }
以下是查找并返回带有条件的子文档的查询-
> db.demo345.aggregate([ ... { ... $match: { UserName: "Robert" } ... }, ... { ... $addFields: { ... UserDetails: { ... $filter: { ... input: "$UserDetails", ... cond: { ... $eq: [ "$$this.isMarried", true ] ... } ... } ... } ... } ... } ... ])
这将产生以下输出-
{ "_id" : ObjectId("5e5404fdf8647eb59e5620ac"), "UserName" : "Robert", "UserDetails" : [ { "isMarried" : true, "CountryName" : "UK" } ] }