MongoDB-এ অ্যারে ফিল্ড থেকে নির্দিষ্ট মানগুলো রাখতে (অন্যান্য বাদ দিয়ে) $setIntersection অপারেটর অ্যাগ্রিগেশন পাইপলাইনে ব্যবহার করা হয়। এটি দুটি অ্যারের সাধারণ (common) উপাদানগুলো রিটার্ন করে।
নমুনা ডেটা তৈরি
> db.filterArrayElementsDemo.insertOne({ "Scores": [10,45,67,78,90,98,99,92] });
{ "acknowledged": true, "insertedId": ObjectId("5cd2d582b64f4b851c3a13c8") }
ডকুমেন্ট দেখুন
> db.filterArrayElementsDemo.find().pretty();আউটপুট:
{
"_id": ObjectId("5cd2d582b64f4b851c3a13c8"),
"Scores": [10, 45, 67, 78, 90, 98, 99, 92]
}
অ্যারে ফিল্টার করার কোয়েরি (শুধু 10, 98, 99 রাখা)
> db.filterArrayElementsDemo.aggregate([
{ $match: { _id: ObjectId("5cd2d582b64f4b851c3a13c8") }},
{ $project: {
Scores: {
$setIntersection: ['$Scores', [10,98,99]]
}
}
}
]);
আউটপুট:
{
"_id": ObjectId("5cd2d582b64f4b851c3a13c8"),
"Scores": [10, 98, 99]
}
ব্যাখ্যা: $setIntersection দুটি অ্যারের ইন্টারসেকশন (সাধারণ উপাদান) বের করে। এখানে মূল অ্যারেতে 10, 98, 99 থাকায় সেগুলোই ফলাফলে এসেছে। অর্ডার সংরক্ষিত নাও থাকতে পারে।