Watch keynotes and sessions from MongoDB.live, our virtual developer conference.

Query document with string and boolean value

Hi, I need to apply 2 filters for quering data from my db - by String field and boolean field.
for example I want to get 20 documents with with fields: boolean: true string:“someString” how I can achieve that ?

You can use the $and operator.

1 Like

There is no real need to break out the $and as it is implicit.

db.collection.find({boolean: true, string:"someString"}).limit(20)

2 Likes

Hi @Zdziszkee_N_A,

Please see Query Documents in the MongoDB manual for examples of queries in the mongo shell, Compass, and drivers.

The relevant example for your question is Specify AND Conditions:

db.foo.find( { boolean: true, string: ‘someString’}).limit(20)

A compound query is implicitly an AND query. You only need to use $and when specifying multiple conditions on the same field name (otherwise repeated field names would overwrite each other in the query object in most languages):

For example, try this in a mongo shell or node interpreter:

foo = {string: ‘someString’, string: ‘someOther’}

In JavaScript the last value of a duplicated property will be the only value set:

{ “string” : “someOther” }

Regards,
Stennie

2 Likes

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.