Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> MongoDB

So sánh nhiều thuộc tính trong MongoDB với $where

Để so sánh nhiều thuộc tính, sử dụng toán tử $where. Tạo collection với document:

> db.comparingMultiplePropertiesDemo.insertOne({"Values":[10,70,60]});
{ "acknowledged" : true, "insertedId" : ObjectId("5cf228fcb64a577be5a2bc0a") }

Hiển thị document:

> db.comparingMultiplePropertiesDemo.find().pretty();

Kết quả:

{ "_id" : ObjectId("5cf228fcb64a577be5a2bc0a"), "Values" : [ 10, 70, 60 ] }

Trường hợp 1: Điều kiện đúng (Values[1] > Values[2] → 70 > 60):

> db.comparingMultiplePropertiesDemo.find({ $where : "this.Values[1] > this.Values[2]" });

Kết quả:

{ "_id" : ObjectId("5cf228fcb64a577be5a2bc0a"), "Values" : [ 10, 70, 60 ] }

Trường hợp 2: Điều kiện sai (Values[1] < Values[2] → 70 < 60):

> db.comparingMultiplePropertiesDemo.find({ $where : "this.Values[1] < this.Values[2]" });

Kết quả: Không trả về document nào vì điều kiện sai.