MongoDB查询以将文档的交集与字段相匹配
为此,请使用aggregate()
。首先让我们创建一个包含文档的集合-
> db.demo393.insertOne( ... { ... Id1: "1", ... Name: "Chris", ... Id2: "100" ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e5e6dd522064be7ab44e804") } > db.demo393.insertOne( ... { ... Id1: "1", ... Name: "Chris", ... Id2: "101" ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e5e6dd522064be7ab44e805") } > db.demo393.insertOne( ... { ... Id1: "3", ... Name: "Chris", ... Id2: "100" ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e5e6dd522064be7ab44e806") } > db.demo393.insertOne( ... { ... Id1: "3", ... Name: "Mike", ... Id2: "101" ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e5e6dd522064be7ab44e807") }
在find()
方法的帮助下显示集合中的所有文档-
> db.demo393.find();
这将产生以下输出-
{ "_id" : ObjectId("5e5e6dd522064be7ab44e804"), "Id1" : "1", "Name" : "Chris", "Id2" : "100" } { "_id" : ObjectId("5e5e6dd522064be7ab44e805"), "Id1" : "1", "Name" : "Chris", "Id2" : "101" } { "_id" : ObjectId("5e5e6dd522064be7ab44e806"), "Id1" : "3", "Name" : "Chris", "Id2" : "100" } { "_id" : ObjectId("5e5e6dd522064be7ab44e807"), "Id1" : "3", "Name" : "Mike", "Id2" : "101" }
以下是将文档的交集与字段相匹配的查询-
> db.demo393.aggregate([ ... { "$match": { "Name": "Chris" } }, ... { "$group": { ... "_id": "$Id1", ... "docs": { "$push": "$$ROOT" }, ... "count": { "$sum": 1 } ... }}, ... { "$match": { ... "count": { "$gt": 1 }, ... "docs": { ... "$all": [ ... { "$elemMatch": { "Id2": "100" } }, ... { "$elemMatch": { "Id2": "101" } } ... ] ... } ... }} ... ])
这将产生以下输出-
{ "_id" : "1", "docs" : [ { "_id" : ObjectId("5e5e6dd522064be7ab44e804"), "Id1" : "1", "Name" : "Chris", "Id2" : "100" }, { "_id" : ObjectId("5e5e6dd522064be7ab44e805"), "Id1" : "1", "Name" : "Chris", "Id2" : "101" } ], "count" : 2 }