JVG
JVG

Reputation: 21170

MongoDB find() to only return results when a certain parameter is set

Looking through the docs here I can't find anything that matches this query. For instance, say I want to do a lookup of the collection products which only returns results for which the parameter maker != undefined. Example set:

[{
    name: 'Obj1',
    maker: 'Maker1'
}.{
    name: 'Obj2'
}.{
    name: 'Obj13',
    maker: 'Maker2'
}]

In the example above, only objects 1 and 3 should be returned.

From the docs, I thought maybe projections might be what I was looking for but this just returns certain fields, rather than limiting results to whether certain field exist.

How can I achieve this?

Upvotes: 0

Views: 130

Answers (1)

JohnnyHK
JohnnyHK

Reputation: 312095

Use the $exists operator to select documents that contain a particular field:

db.products.find({maker: {$exists: true}})

Upvotes: 2

Related Questions