KeplerGrid guide

Add MongoDB array values without new duplicates with $addToSet

Apply a batch of tags with $each and see which values already existed. Check why existing duplicates remain.

Load the practice collection

Run once in mongosh against a development instance with an empty labelledItems practice collection.

const lab = db.getSiblingDB("keplergrid_practice")
lab.labelledItems.insertOne({ _id: "pack-1", tags: ["paper", "paper"] })

In KeplerGrid, open keplergrid_practice.labelledItems with a Read only connection.

Add a batch of tags

Run this command in the same mongosh session. $each makes MongoDB consider each tag separately.

lab.labelledItems.updateOne(
  { _id: "pack-1" },
  { $addToSet: { tags: { $each: ["paper", "ink", "ink"] } } }
)

Only one ink is added. Reopen or rerun the collection query in KeplerGrid to inspect the array. The two pre-existing paper values are still present.

Repeat the same update and check the result

Run the same command again. It matches one document with zero modifications because both submitted values are already present.

The operator creates a missing array field, and a non-array field causes an error. For embedded documents, MongoDB checks the full value, including field order, instead of comparing a single business key.

See how to compare two arrays as sets in an aggregation or revisit the related KeplerGrid walkthrough.