MongoDB: find one document based on the order of $or values? -


findone():

if multiple documents satisfy query, method returns first document according natural order reflects order of documents on disk.

i need similar effect above, except if multiple documents satisfy query, returns 1 comes earliest in $or array.

db.collection.findone({      $or: [          {"apple": "blah"},          {"orange": "blah"},          {"grape": "blah"}      ] }) 

for example, if these documents satisfy above query

[     {"apple": "....", "orange": "....", "grape": "blah"},     {"apple": "....", "orange": "blah", "grape": "...."} ] 

it returns document matched orange (the second 1 above), because orange comes before grape in $or array. similarly, if document matched apple document returned because apple comes earlier in array. how can done?

it sounds want assign "score" each document , return 1 "highest score". 1 way using aggregation framework additional $project , $sort stage initial query. $limit result first or "highest" score found:

db.collection.aggregate([     { "$match": {         "$or": [             { "apple": "blah" },             { "orange": "blah" },             { "grape": "blah" }         ]     }},     { "$project": {         "apple": 1,         "orange": 1,         "grape": 1,         "score": {             "$add": [                 { "$cond": [{ "$eq": [ "$apple", "blah" ] }, 5, 0 ] },                 { "$cond": [{ "$eq": [ "$orange", "blah" ] }, 3, 0 ] },                 { "$cond": [{ "$eq": [ "$grape", "blah" ] }, 1, 0 ] }             ]         }     }},     { "$sort": { "score": -1 } },     { "$limit": 1 } ]) 

that gives "best match" queried items singular result. more or less .findone() operation calculated field.


Comments

Popular posts from this blog

angularjs - ADAL JS Angular- WebAPI add a new role claim to the token -

php - CakePHP HttpSockets send array of paramms -

node.js - Using Node without global install -