Để so sánh nhiều thuộc tính, hãy sử dụng $ where trong MongoDB. Hãy để chúng tôi tạo một bộ sưu tập với các tài liệu -
> db.demo223.insertOne({"Scores":[56,78]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e3ee4ca03d395bdc2134730")
}
> db.demo223.insertOne({"Scores":[88,45]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e3ee4d103d395bdc2134731")
}
> db.demo223.insertOne({"Scores":[98,79]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e3ee4d803d395bdc2134732")
} Hiển thị tất cả các tài liệu từ một bộ sưu tập với sự trợ giúp của phương thức find () -
> db.demo223.find();
Điều này sẽ tạo ra kết quả sau -
{ "_id" : ObjectId("5e3ee4ca03d395bdc2134730"), "Scores" : [ 56, 78 ] }
{ "_id" : ObjectId("5e3ee4d103d395bdc2134731"), "Scores" : [ 88, 45 ] }
{ "_id" : ObjectId("5e3ee4d803d395bdc2134732"), "Scores" : [ 98, 79 ] } Sau đây là truy vấn để so sánh nhiều thuộc tính trong MongoDB -
> db.demo223.find({ $where : "this.Scores[0] > this.Scores[1]" }); Điều này sẽ tạo ra kết quả sau -
{ "_id" : ObjectId("5e3ee4d103d395bdc2134731"), "Scores" : [ 88, 45 ] }
{ "_id" : ObjectId("5e3ee4d803d395bdc2134732"), "Scores" : [ 98, 79 ] }