在MongoDB中查詢找到“發貨”地址等於發貨地址的文件


若要檢查相等性並獲取文件,請使用MongoDB中的$where。我們使用文件建立一個集合−

> db.demo589.insertOne({deliveryAddress:"US",billingAddress:"UK"});{
   "acknowledged" : true, "insertedId" : ObjectId("5e92c117fd2d90c177b5bccc")
}
> db.demo589.insertOne({deliveryAddress:"US",billingAddress:"US"});{
   "acknowledged" : true, "insertedId" : ObjectId("5e92c11bfd2d90c177b5bccd")
}
> db.demo589.insertOne({deliveryAddress:"US",billingAddress:"AUS"});{
   "acknowledged" : true, "insertedId" : ObjectId("5e92c11ffd2d90c177b5bcce")
}
> db.demo589.insertOne({deliveryAddress:"UK",billingAddress:"US"});{
   "acknowledged" : true, "insertedId" : ObjectId("5e92c127fd2d90c177b5bccf")
}

使用find()方法從集合中顯示所有文件−

> db.demo589.find();

這將產生以下輸出−

{ "_id" : ObjectId("5e92c117fd2d90c177b5bccc"), "deliveryAddress" : "US", "billingAddress" : "UK" }
{ "_id" : ObjectId("5e92c11bfd2d90c177b5bccd"), "deliveryAddress" : "US", "billingAddress" : "US" }
{ "_id" : ObjectId("5e92c11ffd2d90c177b5bcce"), "deliveryAddress" : "US", "billingAddress" : "AUS" }
{ "_id" : ObjectId("5e92c127fd2d90c177b5bccf"), "deliveryAddress" : "UK", "billingAddress" : "US" }

以下是查詢“發貨”地址等於收貨地址並獲取文件的方法−

> db.demo589.find( { $where: "this.deliveryAddress == this.billingAddress" } );

這將產生以下輸出−

{ "_id" : ObjectId("5e92c11bfd2d90c177b5bccd"), "deliveryAddress" : "US", "billingAddress" : "US" }

更新於:2020年5月15日

140次瀏覽

開啟你的 職業生涯

透過完成課程獲得證書

開始
廣告
© . All rights reserved.