简体   繁体   中英

select on result of subtract. mongodb

Assume there is collection like:

db.test.insert([{"f1":100,"f2":150},{"f1":120,"f2":541},{"f1":125,"f2":140}])

How can I create similar query mongodb

Select count(*) from test where  (f2-f1)<100 

I did some tries, but not work:

db.test.aggregate([{ $match: {} }, { $project: { _id : 0,name : 1, r1: {$subtract:["$f2", "$f1"]} }}])

First use $project to create a result-set with the calculated values. Then use $match to filter out those values which don't match your condition.

db.test.aggregate(
    { $project: { _id : 0,
                  name : 1, 
                  difference: {$subtract:["$f2", "$f1"]}
                }
    },
    { $match: { difference: { $lt: 100 }
              }
    })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM