Translation of sql query to Mongo languague

孤者浪人 提交于 2019-12-12 01:53:16

问题


I am trying to do the following query in Mongo:

SELECT * 
FROM events 
WHERE v1 - v2 > 20;

where v1 and v2 are names of columns in the SQL DB.

how can I translate it to Mongo Languague?


回答1:


Assume you have these documents in your events:

{
    "_id" : ObjectId("54cdfde528bb923955eff8b4"),
    "v1" : 35,
    "v2" : 10
}

/* 1 */
{
    "_id" : ObjectId("54cdfde928bb923955eff8b5"),
    "v1" : 10,
    "v2" : 20
}

You cant use a simple find() query. You should use aggregation:

db.events.aggregate(
[    
    { $project : { 'diff' : { $subtract : ['$v1', '$v2'] }, v1 : 1, v2 : 1 } },
    { $match : { diff : { $gt : 20} } },
    { $project : { v1 : 1, v2 : 1 } },
]).result

the result is:

{
    "0" : {
        "_id" : ObjectId("54cdfde528bb923955eff8b4"),
        "v1" : 35,
        "v2" : 10
    }
}


来源:https://stackoverflow.com/questions/28261506/translation-of-sql-query-to-mongo-languague

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!