I suppose you documents look like this:
{ "_id" : ObjectId("55c87313fc92af6b6b2f9497"), "name" : "abc", "age" : "", "city" : "delhi" }
{ "_id" : ObjectId("55c87314fc92af6b6b2f9498"), "name" : "abc", "age" : "", "city" : "delhi" }
{ "_id" : ObjectId("55c87314fc92af6b6b2f9499"), "name" : "abc", "age" : "", "city" : "delhi" }
{ "_id" : ObjectId("55c87319fc92af6b6b2f949a"), "name" : "abc", "age" : 2, "city" : "delhi" }
{ "_id" : ObjectId("55c8731cfc92af6b6b2f949b"), "name" : "abc", "age" : 3, "city" : "delhi" }
{ "_id" : ObjectId("55c87320fc92af6b6b2f949c"), "name" : "abc", "age" : 4, "city" : "delhi" }
{ "_id" : ObjectId("55c87324fc92af6b6b2f949d"), "name" : "abc", "city" : "delhi" }
{ "_id" : ObjectId("55c87325fc92af6b6b2f949e"), "name" : "abc", "city" : "delhi" }
{ "_id" : ObjectId("55c87326fc92af6b6b2f949f"), "name" : "abc", "city" : "delhi" }
Here I suppose age
type is Double.
You need to use the $exists
and the $type
operators. The first one to filter the documents where age
is present and the latter where its value is not blank.
db.collection.aggregate([
{ "$match": { "name": "abc", "age": { "$exists": true, "$type": 1 }}}
])
The shorter way to write the above is:
db.collection.aggregate([
{ "$match": { "name": "abc", "age": { "$type": 1 }, "city": "delhi" }}
])
because the $type
operator matches only if the field exists and is of the specified type.
If $match
is the only pipeline operator in your aggregation then you don't need aggregation. Simply use the .find
method.
db.collection.find({'name': 'abc', age: {$type: 1}, city: 'delhi' })
Output:
{ "_id" : ObjectId("55c87319fc92af6b6b2f949a"), "name" : "abc", "age" : 2, "city" : "delhi" }
{ "_id" : ObjectId("55c8731cfc92af6b6b2f949b"), "name" : "abc", "age" : 3, "city" : "delhi" }
{ "_id" : ObjectId("55c87320fc92af6b6b2f949c"), "name" : "abc", "age" : 4, "city" : "delhi" }