Query an array field containing all given values in MongoDB/Mongoose

If you want to find records that have a given set of values in common in an array field, the MongoDB $all operator comes in handy. In my case this was necessary to get all groups that two users have in common.

The $all Operator

To understand the $all operator, we take a look at the following schema:

const mongoose = require('mongoose');

//...

const groupSchema = mongoose.Schema(
  {
    // ...
    members: [
      {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'User',
        autopopulate: true,
        index: true,
      },
    ],
  },
);

//...

module.exports = mongoose.model("Group", groupSchema);

If we now have two users firstUser and secondUser given and want to find all groups those users have in common, thus they are both members of, we simply call

Group.find({
    members: { $all: [firstUser, secondUser] },
})

Considering the following group documents:

{
    name: "Common Group",
    // ...
    members: [
        { "$oid": "FIRST_USER_ID" }, 
        { "$oid": "SECOND_USER_ID" }, 
        { "$oid": "OTHER_USER_ID" }
    ]
    // ...    
},
{
    name: "Uncommon Group",
    // ...
    members: [
        { "$oid": "FIRST_USER_ID" }, 
        { "$oid": "OTHER_USER_ID" }
    ]
    // ...    
}

Calling the query for FIRST_USER_ID and SECOND_USER_ID, we will receive the following group:

{
    name: "Common Group",
    // ...
    members: [
        { "$oid": "FIRST_USER_ID" }, 
        { "$oid": "SECOND_USER_ID" }, 
        { "$oid": "OTHER_USER_ID" }
    ]
    // ...    
},

Written by
Christian Konrad
Web Developer, Product Manager and UI Designer in Frankfurt a. Main, Germany. My specialization is generalization.
More to read