Sử dụng toán tử $where kết hợp với logic JavaScript. Tạo collection với document:
> 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") }
Hiển thị tất cả document:
> db.sameValueMultipleTimesDemo.find().pretty();
Kết quả
{ "_id" : ObjectId("5cefc4e6ef71edecf6a1f6b9"), "ListOfPrice" : [ { "Price" : 110 }, { "Price" : 130 }, { "Price" : 145 } ] }
{ "_id" : ObjectId("5cefc4e7ef71edecf6a1f6ba"), "ListOfPrice" : [ { "Price" : 110 }, { "Price" : 178 }, { "Price" : 110 } ] }
Truy vấn tìm document có giá trị Price = 110 xuất hiện > 1 lần trong mảng ListOfPrice:
> db.sameValueMultipleTimesDemo.find({
"$where": function() {
return this.ListOfPrice.filter(function(p) {
return p.Price == 110;
}).length > 1;
}
});
Kết quả
{ "_id" : ObjectId("5cefc4e7ef71edecf6a1f6ba"), "ListOfPrice" : [ { "Price" : 110 }, { "Price" : 178 }, { "Price" : 110 } ] }