簡體   English   中英

如何選擇字段總和大於 MongoDB 中的值的位置

[英]How to select where sum of fields is greater than a value in MongoDB

使用 MongoDB,我將如何編寫此常規 SQL 語句?

SELECT * FROM table WHERE (field1+field2+field3) > 1

我一直在搞亂 $group、$project、$add 等。我覺得我在圍繞解決方案跳舞,但無法弄清楚。

最簡單的方法是使用$where (我不是說不可能通過聚合來做到這一點)

db.table.find({$where: function() {
   return this.field1 + this.field2 + this.field3 > 1
   // most probably you have to handle additional cases if some of the fields do not exist.
}}

它的優點是簡單直觀,而缺點是:

要求數據庫處理集合中每個文檔的 JavaScript 表達式或函數。

如果您需要經常執行此類搜索,我會繼續創建一個新字段,該字段將存儲 3 個字段的總和並在其上放置索引。 缺點是您必須增加應用程序邏輯。

> db.test.drop()
> db.test.insert({ "_id" : 0, "a" : 1, "b" : 1, "c" : 1 })
> db.test.insert({ "_id" : 1, "a" : 1, "b" : 1, "c" : 2 })
> db.test.aggregate([
    { "$project" : { 
        "sum" : { "$add" : ["$a", "$b", "$c" ] } 
    } }, 
    { "$match" : { 
        "sum" : { "$gte" : 4 } 
    } }
])
{ "_id" : 1, "sum" : 4 }

這是一篇舊帖子,但這可能有助於尋找其他解決方案的人。 我發現這比$where.aggregate()更簡單。

> db.foo.insert({"a": 17, "b": 8})
> db.foo.find({$expr: {$gt: [{$add: ["$a", "$b"]}, 25]}})   // no result
> db.foo.find({$expr: {$gt: [{$add: ["$a", "$b"]}, 24]}})
{ "_id" : ObjectId("602acf55a69fb564c11af7db"), "a" : 17, "b" : 8 }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM