问题
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