简体   繁体   中英

How to make a query in MongoDB using a JSON?

is there anyway to make a query in MongoDB using a JSON and returning a object if one field of the json matches with some in the database? for example, I have the this object called keysArray

 { house: 'true', garden: 'false' } 

and I would like to make a query in Mongo passing this object as a query field and return if some object in my database matches with at least one of those fields :

keysArray.forEach(function(key){
            collection.find({keysArray}, function(err, propertyMatch){
                console.log(propertyMatch)
            })
        })

I got no objects back, even if I have one object in my database that matches these fields.

Thanks in advance

...and I would like to make a query in Mongo passing this object as a query field and return if some object in my database matches with at least one of those fields.

It sounds like OR logic - if I understood it well.
On this specific case it's not possible to pass in JSON-like object to query as it would be a implicit AND logic condition.
So you should build first a OR expression and use it in collection.find() , something like this:

var myjson = {'status': 32, 'profile': {$exists: false}};

function build_logic_or(json) {
    var orExpr = [];

    for (var field in json) {
        var expr = {};
        expr[field] = json[field];
        orExpr.push(expr);
    }

    return {'$or': orExpr};
}

It would build an expression like this:

{"$or":[{"status":32},{"profile":{"$exists":false}}]}

So:

db.collection.find(build_logic_or(myjson))

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