javascript - How can I check field exist or not in mongo db before querying to mongodb? -
i have run dynamic query on collections in such way user enters collection name, field name , field value , have first of check whether field name supplied user exists in collection , if not have run query shown in example below.
for example: if user enters collection name user
, field name type
, field value article
. , based on parameters have query follows:
1) if type
field exists in collection user
, query be:
query = user.find({type:'article'})
2) if type not field of collection user
, query be:
query = user.find()
i tried $exists
not working me. , how can use $exists
before querying? because collection, field name , field value dynamic. , how can check type
field exists or not in user
collection?
i tried solution $exists
, want know if there way it.
as @philipp mentioned in comment, bound bump performance issues need perform full-collection scan without use of indexes. using $exists
, query return fields equal null. suppose want first find records have field type
set , isn't null, use combination of $ne
operator. closest try count of field , determine query object based on field count:
var type_count = db.user.find({"type": {$exists: true, $ne: null}}).count(); var query = (type_count > 0) ? {"type": "article"} : {}; db.user.find(query);
Comments
Post a Comment