mongo snippets: array cheatsheet

Cheatsheet - Array Of Values

A short cheat sheet for working with arrays in mongodb queries and aggregations. Inspired by: Mongo Doc - Update Array Operator

document structure#

For all following examples we assume a collection named “arrays” with at least on document of the following structure:

{
  "tags": ["A", "B", "C"]
}

create#

Creation is very straight forward so we will skip this part here.

query#

Basic query operation on elements.

contains an element

db.arrays.find({
    tags: "A",
  }).toArray();

contains one of multi elements

db.arrays.find({
    tags: {
      $in: ["A", "C"],
    },
  }).toArray();

contains all elements

db.arrays.find({
    tags: { 
      $all: ["A", "C"] 
    },
  }).toArray();

does not contain

db.arrays.find({
    tags: {$ne: "C"},
  }).toArray();

or with multiple values:

db.arrays.find({
    tags: {$nin: ["tag a", "tag c"]},
  }).toArray();

other conditions

There are other conditions than equality like greater/less and some more. For a full list pleas refere to the documentation:

update#

Update will only update a single document, be aware of that. If you want to modifiy all documents use {multi: true} or db.collection.updateMany().

add#

add one element

db.arrays.update(
  {},
  {
    $push: {
      tags: "X",
    },
  }
);

add multi elements

db.arrays.update(
  {},
  {
    $push: {
      tags: {
        $each: ["Y", "Z"],
      },
    },
  }
);

add only if not existing

db.arrays.update(
  {},
  {
    $addToSet: {
      tags: {
        $each: ["C", "D"],
      },
    },
  }
);

find and replace values#

find first occurence and change that value

db.arrays.updateMany(
  { tags: "A" },
  {
    $set: {
      "tags.$": "C",
    },
  }
);

find all occurence and change all of their values

db.arrays.updateMany(
  {},
  {
    $set: {
      "tags.$[filter]": "C",
    },
  },
  {
    arrayFilters: [
      {
        filter: "A",
      },
    ],
  }
);

More on arrayFilters you can find in Mongo Doc - Positional Filter.

override whole array of a single document#

db.arrays.update(
  {},
  {
    tags: ["A", "B", "C"],
  }
);

remove#

This removes all matching tags, also if they are doubled inserted.

db.arrays.update(
  {},
  {
    $pull: {
      tags: "A",
    },
  },
  { multi: true }
);

remove multiple values

db.arrays.update(
  {},
  {
    $pull: {
      tags: {
        $in: ["A", "B"],
      },
    },
  }
);

sorting#

You can sort your array after inserting a value.

sorting by with push

db.arrays.update(
  {},
  {
    $push: {
      tags: {
        $each: ["X"],
        $sort: -1,
      },
    },
  }
);

sorting fields without inserting

You can make an empty push and let monog db sort the fields.

db.arrays.update(
  {},
  {
    $push: {
      tags: {
        $each: [],
        $sort: 1,
      },
    },
  }
);