具有 criteria 的查询 MongoDB 以查找并返回次级文档?
让我们创建一个文档集合 −
> 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" } ] }
广告