Query a field for multiple values
Learn how to use the MongoDB $in operator
Thu, 20 Dec 2018
Sometimes you need to query a field within your schema and match it to multiple values. I needed to do this when I had a function that needed to return all users who’s office matched either of the two values I provided.
$in Operator
The $in
operator is an operator in Mongo that will return a document for any of the values in the supplied array that return true;
{ field: { $in: [<value1>, <value2>, ... <valueN> ] } }
Schema
'use strict';
//import dependency
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
//create new instance of the mongoose.schema. the schema takes an
//object that shows the shape of your database entries.
var usersSchema = new Schema({
first: String,
last: String,
email: String,
role: String,
lastLogin: Date,
office: String
});
module.exports = mongoose.model("Users", usersSchema);
API
I’m skipping the bulk of the api and just showing the function
User.find({
'office': { $in: [req.params.office, "Company"]}
}