MongoDB में सरणी में किसी मान की एकाधिक घटनाएं (डुप्लिकेट) वाले दस्तावेज़ ढूंढने के लिए $where ऑपरेटर के साथ JavaScript फ़िल्टर का उपयोग करें।
उदाहरण
कीमतों की सरणी वाले दस्तावेज़ बनाएं:
> db.sameValueMultipleTimesDemo.insertOne(
{"ListOfPrice": [{"Price": 110}, {"Price": 130}, {"Price": 145}]}
);
{ "acknowledged" : true, "insertedId" : ObjectId("5cefc4e6ef71edecf6a1f6b9") }
> db.sameValueMultipleTimesDemo.insertOne(
{"ListOfPrice": [{"Price": 110}, {"Price": 178}, {"Price": 110}]}
);
{ "acknowledged" : true, "insertedId" : ObjectId("5cefc4e7ef71edecf6a1f6ba") }
दस्तावेज़ देखें:
> db.sameValueMultipleTimesDemo.find().pretty();
{ "_id" : ObjectId("5cefc4e6ef71edecf6a1f6b9"), "ListOfPrice" : [ { "Price" : 110 }, { "Price" : 130 }, { "Price" : 145 } ] }
{ "_id" : ObjectId("5cefc4e7ef71edecf6a1f6ba"), "ListOfPrice" : [ { "Price" : 110 }, { "Price" : 178 }, { "Price" : 110 } ] }
Price 110 एक से अधिक बार वाले दस्तावेज़ ढूंढें
> db.sameValueMultipleTimesDemo.find({
"$where": function() {
return this.ListOfPrice.filter(function(p) {
return p.Price == 110;
}).length > 1;
}
});
आउटपुट:
{ "_id" : ObjectId("5cefc4e7ef71edecf6a1f6ba"), "ListOfPrice" : [ { "Price" : 110 }, { "Price" : 178 }, { "Price" : 110 } ] }
व्याख्या:
this.ListOfPrice- सरणी तक पहुंच.filter(...)- Price 110 वाले तत्व फिल्टर करता है.length > 1- एक से अधिक घटनाएं जांचता है
चेतावनी: $where धीमा है। बड़े कलेक्शन के लिए एग्रीगेशन विकल्प:
db.collection.aggregate([
{$unwind: "$ListOfPrice"},
{$group: {_id: "$_id", count: {$sum: {$cond: [{$eq: ["$ListOfPrice.Price", 110]}, 1, 0]}}, doc: {$first: "$$ROOT"}}},
{$match: {count: {$gt: 1}}},
{$replaceRoot: {newRoot: "$doc"}}
])
यह इंडेक्स का उपयोग कर सकता है और अधिक स्केलेबल है।