如果MongoDB中至少有一个元素匹配,如何聚合两个列表?
> db.demo456.insertOne( ... { _id: 101, StudentName: ["Chris", "David"] } ... ); { "acknowledged" : true, "insertedId" : 101 } > > db.demo456.insertOne( ... { _id: 102, StudentName: ["Mike", "Sam"] } ... ); { "acknowledged" : true, "insertedId" : 102 } > db.demo456.insertOne( ... { _id: 103, StudentName: ["John", "Jace"] } ... ); { "acknowledged" : true, "insertedId" : 103 } > db.demo456.insertOne( ... { _id: 104, StudentName: ["Robert", "John"] } ... ); { "acknowledged" : true, "insertedId" : 104 }
在find()
方法的帮助下显示集合中的所有文档-
> db.demo456.find();
这将产生以下输出-
{ "_id" : 101, "StudentName" : [ "Chris", "David" ] } { "_id" : 102, "StudentName" : [ "Mike", "Sam" ] } { "_id" : 103, "StudentName" : [ "John", "Jace" ] } { "_id" : 104, "StudentName" : [ "Robert", "John" ] }
以下是如果至少一个元素匹配则汇总两个列表的查询-
> db.demo456.aggregate([ ... {$unwind:"$StudentName"}, ... {$group:{_id:"$StudentName", combine:{$addToSet:"$_id"}, size:{$sum:1}}}, ... {$match:{size: {$gt: 1}}}, ... {$project:{_id: 1, combine:1, size: 1, combine1: "$combine"}}, ... {$unwind:"$combine"}, ... {$unwind:"$combine1"}, ... {$group:{_id:"$combine", l:{$first:"$_id"}, size:{$sum: 1}, set: {$addToSet:"$combine1"}}}, ... {$sort:{size:1}}, ... {$group:{_id: "$l", combineIds:{$last:"$set"}, size:{$sum:1}}}, ... {$match: {size:{$gt:1}}} ... ])
这将产生以下输出-
{ "_id" : "John", "combineIds" : [ 103, 104 ], "size" : 2 }