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"]}
  }
Buy Me A CoffeeDigitalOcean Referral Badge
Loading...
Edward Beazer

Edward Beazer - I just like to build shit. Sometimes I get stuck for hours, even days while trying to figure out how to solve an issue or implement a new feature. Hope my tips and tutorials can save you some time.

DigitalOcean Referral Badge