Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mongoose query same field with different values

Tags:

Is there a way to user mongoose.find({title:'some title'}) to query the same field with multiple values? For example something like this mongoose.find({title:'some title', title:'some other title'}) sends back only documents matching title:'some other title is there a way to accomplish this ?

like image 442
JohnSnow Avatar asked Mar 31 '17 17:03

JohnSnow


People also ask

Can Mongoose queries be chained?

Mongoose lets you structure queries using chaining or, equivalently, using POJOs in a single function call. Model.

What is skip and limit in mongoose?

The limit method will be used to return the maximum number of results from the collection, while the skip method is used to skip the number of documents from the collection in MongoDB. If we have one collection name as a student, student collection contains a hundred documents in it.

What does Mongoose findById return?

Return value findById returns the document where the _id field matches the specified id . If the document is not found, the function returns null .

Does Mongoose query return a promise?

Mongoose async operations, like . save() and queries, return Promises/A+ conformant promises. This means that you can do things like MyModel.


2 Answers

You should use the MongoDB $in operator -

mongoose.find({title: {$in: ['some title', 'some other title']}})

You provide an array to $in operator and it will return all the documents which have an exact title in the array specified.

like image 192
Jyotman Singh Avatar answered Nov 15 '22 16:11

Jyotman Singh


Found this in 2021 with the same question. It seems the $in operator is no longer necessary. As long as you pass find() an array of items, it will search for all of them.

Ex:

Furniture.find({
  room: [ 'first_id', 'second_id' ]
})

This will return the documents where room is the first OR second id.

Can be written in a query string like:

?room=first_id&room=second_id

There's no parsing needed—Node parses this into an array automatically.

like image 45
terraforme Avatar answered Nov 15 '22 16:11

terraforme