MongoDB and distinct values in arrays

This post is a mini-tutorial on how to deal with array fields in MongoDB, specifically arrays of items that may or may not be duplicated.

Let's create a collection of unicorns, smilarly to The Little MongoDB Book examples:

Find should now return something like this, the _ids will vary:

Adding a value into an array

We've found out that our unicorn Scott also loves playing games, so lets push a new value into our document's loves array:

Using push, we could insert into our the same value multiple times.

Pushing a value if its unique

We have found out that all our unicorns love movies and want to update the whole collection. Unfortunately Scott already has got movies in his loves field. As shown here, we can use addToSet, which won't add a duplicated value to an array:

The third parameter of update is upsert(false by default). The fourth is multi which makes the query update every document that matches the criteria (false by default meaning that it only updates the first one). You can read more here.

Getting the distinct values

Removing duplicate values from array

Lets say that we missused push and added some duplicate values into our array. Here's now to fix this:

I hope I could help a little bit, especially with removing duplicate values.

Comments

Popular posts from this blog

Android Virtual Machine and non-ASCII characters the path

Installing FANN on Java project and NativeLibrary.loadLibrary problems with 32bit/64bit