检查 MongoDB 中内部阵列的特定字段的重复项
要检查内部阵列中的重复项,请在 MongoDB 中使用 aggregate()。让我们创建一个包含文档的集合 −
> 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 }
广告