如何獲取 MongoDB 中 `陣列` 中大於 50 的`值`(而不是 json 陣列)?


要避免獲取 json 陣列並獲取值陣列, 請使用 $in. 對於大於, 請使用 MongoDB $gt. 我們建立一個包含文件的集合 -

> db.demo50.save({"Value":40});
WriteResult({ "nInserted" : 1 })
> db.demo50.save({"Value":100});
WriteResult({ "nInserted" : 1 })
> db.demo50.save({"Value":20});
WriteResult({ "nInserted" : 1 })
> db.demo50.save({"Value":510});
WriteResult({ "nInserted" : 1 })

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

> db.demo50.find();

這將產生以下輸出 -

{ "_id" : ObjectId("5e270c02cfb11e5c34d89903"), "Value" : 40 }
{ "_id" : ObjectId("5e270c05cfb11e5c34d89904"), "Value" : 100 }
{ "_id" : ObjectId("5e270c07cfb11e5c34d89905"), "Value" : 20 }
{ "_id" : ObjectId("5e270c11cfb11e5c34d89906"), "Value" : 510 }

以下是 MongoDB 中大於 50 的值陣列的查詢 -

> listOfValues = db.demo50.distinct("_id", {Value:{$gt:50}});
[
   ObjectId("5e270c05cfb11e5c34d89904"),
   ObjectId("5e270c11cfb11e5c34d89906")
]
> db.demo50.find({_id:{$in:listOfValues}});

這將產生以下輸出 -

{ "_id" : ObjectId("5e270c05cfb11e5c34d89904"), "Value" : 100 }
{ "_id" : ObjectId("5e270c11cfb11e5c34d89906"), "Value" : 510 }

更新於: 2020-04-03

87 人瀏覽

啟動你的 職業生涯

完成課程,獲得認證

開始
廣告