Hii there,
I am using MongoDB with NodeJS and using a module Mongoose(a wrapper around Mongodb) around it to do my database operations. I need to check 3-4 values to be unique in the collection. I can simply do it by
MyModel.find();
but it checks for the given conditions to be present in a single document.For e.g. I have three values passed in the conditions they should be checked across all documents and if single one is met it should return a document.
Like if i have passed field1,field2 ,field3 if a document matches just field1 it should be returned.
I want to do this because then I have to write 3 different
MyModel.find();
queries for three fields and it will be quite messy.
Note: I have marked unique property to true in schema, but I need to write a explicit check.
As Girish Mentioned, you can use $in operator if you want to match documents from one of the values of a particular field. ex: find all documents where a=10 or 20
If your conditions to match occur across the fields, then use $or operator. example: to find all documents where a=10 or b=20, its syntax goes like this: Model.find({ $or: [ { a: 10 }, { b: 20 } ] })
You can use $in operator.
Ex. query.
Mymodel.find({ fieldname : { $in : [field_value_1, field_value_2,field_value_3] } })
This will find all documents with fieldname set to any of those three field values.
More ref. docs.mongodb.com/manual/reference/operator/query/… mongoosejs.com/docs/queries.html
Abhishek Pathak
Javascript Developer
Better use the findOne query. It is faster than find.
You said fields, so let's suppose that means name, email, and username.
Now, if you want to check if the value lets say, "hashnode" is present in any of these,
you simply go for,
User.findOne({ $or: [ { name: "hashnode" }, { email: "hashnode"}, { username: "hashnode" } ] }).exec()