MongoDB 过滤多个子文档?
若要在 MongoDB 中过滤多个子文档,请使用 aggregate()。我们创建一个带有文档的集合 −
> db.demo200.insertOne( ... { ... "Id":"101", ... "details1":[ ... { ... "isActive":true, ... "SubjectName":"MySQL" ... },{ ... "isActive":false, ... "SubjectName":"Java" ... } ... ], ... "details2":[ ... { ... "isActive":false, ... "Name":"David" ... },{ ... "isActive":true, ... "Name":"Mike" ... } ... ] ... } ...); { "acknowledged" : true, "insertedId" : ObjectId("5e3c374f03d395bdc21346e4") }
使用 find() 方法从集合中显示所有文档 −
> db.demo200.find();
这样会产生以下输出 −
{ "_id" : ObjectId("5e3c374f03d395bdc21346e4"), "Id" : "101", "details1" : [ { "isActive" : true, "SubjectName" : "MySQL" }, { "isActive" : false, "SubjectName" : "Java" } ], "details2" : [ { "isActive" : false, "Name" : "David" }, { "isActive" : true, "Name" : "Mike" } ] }
以下是用于过滤多个子文档的查询 −
> var out= [ ... { ... "$match": { ... "Id": "101", ... "details1.isActive": true, ... "details2.isActive": true ... } ... }, ... { "$unwind": "$details1" }, ... { "$unwind": "$details2" }, ... { ... "$match": { ... "details1.isActive": true, ... "details2.isActive": true ... } ... }, ... { ... "$group": { ... "_id": { ... "_id": "$_id", ... "Id": "$Id" ... }, ... "details2": { "$addToSet" : "$details2" }, ... "details1": { "$addToSet" : "$details1" } ... } ... }, ... { ... "$project": { ... "_id": 0, ... "Id": "$_id.Id", ... "details2": 1, ... "details1": 1 ... } ... } ...] > > db.demo200.aggregate(out)
这样会产生以下输出 −
{ "details2" : [ { "isActive" : true, "Name" : "Mike" } ], "details1" : [ { "isActive" : true, "SubjectName" : "MySQL" } ], "Id" : "101" }
广告