要检查内部数组中的重复项,请aggregate()
在MongoDB中使用。让我们创建一个包含文档的集合-
> db.demo347.insertOne( ... { ... "details": { ... "details1": [ ... { ... Name: "Chris", ... Age: 21 ... } ... ... ] ... } ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e5532eaf8647eb59e5620af") } > db.demo347.insertOne( ... { ... "details": { ... "details1": [ ... { ... Name: "David", ... Age: 22 ... } ... ... ] ... } ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e55330af8647eb59e5620b0") } > db.demo347.insertOne( ... { ... "details": { ... "details1": [ ... { ... Name: "Chris", ... Age: 21 ... } ... ... ] ... } ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e55331cf8647eb59e5620b1") }
在find()
方法的帮助下显示集合中的所有文档-
> db.demo347.find();
这将产生以下输出-
{ "_id" : ObjectId("5e5532eaf8647eb59e5620af"), "details" : { "details1" : [ { "Name" : "Chris", "Age" : 21 } ] } } { "_id" : ObjectId("5e55330af8647eb59e5620b0"), "details" : { "details1" : [ { "Name" : "David", "Age" : 22 } ] } } { "_id" : ObjectId("5e55331cf8647eb59e5620b1"), "details" : { "details1" : [ { "Name" : "Chris", "Age" : 21 } ] } }
以下是检查特定字段重复项的查询-
> db.demo347.aggregate([ ... {"$unwind": "$details"}, ... {"$unwind": "$details.details1"}, ... {"$group" : { "_id": "$details.details1.Name", "count": { "$sum": 1 } } }, ... {"$match": { "_id" :{ "$ne" : null } , "count" : { "$gt": 1} } } ... ])
这将产生以下输出-
{ "_id" : "Chris", "count" : 2 }