MongoDB-এ অ্যারেতে কোনো নির্দিষ্ট মান একাধিকবার আছে কিনা তা যাচাই করতে $where অপারেটর সহ জাভাস্ক্রিপ্ট ফাংশন ব্যবহার করুন।
উদাহরণ
দুটি ডকুমেন্ট তৈরি করুন (দ্বিতীয়টিতে Price 110 দুবার):
> 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 olan সব এলিমেন্ট ফিল্টার করে।.length > 1— একাধিকবার থাকলে true রিটার্ন করে।
সতর্কতা: $where জাভাস্ক্রিপ্ট এক্সিকিউশন ব্যবহার করে, ধীর। MongoDB ৪.৪+ এ $function বা এগ্রিগেশন ($size, $filter) ব্যবহার করুন।
আধুনিক বিকল্প (MongoDB ৪.৪+): $expr + $filter
db.sameValueMultipleTimesDemo.find({
$expr: {
$gt: [
{ $size: { $filter: { input: "$ListOfPrice", cond: { $eq: ["$$this.Price", 110] } } } },
1
]
}
});