compare two fields of same document [duplicate]

2019-07-15 21:21发布

问题:

This question already has an answer here:

  • MongoDb query condition on comparing 2 fields 4 answers

I'm trying to query a huge mongo collection which have around 50 + Million records. In the mongo query , I only need few fields. Object ID and MD5 which is present in the document. For that , I did

Query :

db.getCollection('experimental_engine').find({},{"md5":1,"_id":1}) 

Result :

/* 1 */
{
    "_id" : "5cee41f2ca4e0ebf567ffd1be5cdaf1f",
    "md5" : "1d813cb29082b13efe572e8088f006dd"
}

/* 2 */
{
    "_id" : "fcd79aac0d5c5ebdfd0fa389368ab6f3",
    "md5" : "13a1a6cd5c8f1c5eaf3d409f4d809889"
}


/* 3 */
{
    "_id" : "2a0b42d01892bd9b7368d045a4c7862c",
    "md5" : "2a0b42d01892bd9b7368d045a4c7862c"
}


................

Now , i wanted to match both "_id" and "md5" and get only matching values ( _id = md5 ) .

Do mongo command support match values for two keys ?

Any suggestion please ?

回答1:

You can use $expr which allows the use of aggregation expressions within the query language.

db.collection.find({ "$expr": { "$eq": [ "$_id" , "$md5" ] } })

or with aggregation

db.collection.aggregate([
  { "$match": { "$expr": { "$eq": [ "$_id" , "$md5" ] } } }
])