Iterate MongoDB Documents 625

Have a Database Problem? Speak with an Expert for Free
Get Started >>

Introduction

In this article we’ll show you how to iterate on MongoDB Documents through a couple different methods in the MongoDB shell. The documents in MongoDB contain data in JSON format, i.e. key-value pairs. The documents, in turn, are stored in collections. We use the find method to get all the documents inside a collection. The find method will return all the documents in JSON format.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
> db.dogs.find().pretty()
{
        "_id" : ObjectId("5d4e80d06945575300747d65"),
        "name" : "Tyson",
        "breed" : "American Pitbull",
        "gender" : "Male"
}
{
        "_id" : ObjectId("5d4e80e76945575300747d66"),
        "name" : "Rambo",
        "breed" : "German Shephard",
        "gender" : "Male"
}
{
        "_id" : ObjectId("5d4e81336945575300747d67"),
        "name" : "Lala",
        "breed" : "German Shephard",
        "gender" : "Female"
}
{
        "_id" : ObjectId("5d4e81476945575300747d68"),
        "name" : "Joyi",
        "breed" : "Pug",
        "gender" : "Female"
}
{
        "_id" : ObjectId("5d4e81596945575300747d69"),
        "name" : "Scooby",
        "breed" : "Great Dane",
        "gender" : "Male"
}
{
        "_id" : ObjectId("5d4e81856945575300747d6a"),
        "name" : "Max",
        "breed" : "Labrador",
        "gender" : "Male"
}
>

Above we used the find method along with the pretty method to get all the documents in the dogs collection. We got all the documents inside it. We can also use the find method with query and projection to find the specific data. But what if we want to iterate these documents, instead of getting all the data at once? Yes, we have couple of methods for it.

Iterate through documents

forEach method

Iterating is one important aspect of the programming world. We use various loops for iterating in programming languages such as for, while, do-while and switch. We may also need to iterate through the data in a collection in MongoDB. MongoDB provides the forEach method for iterating. Suppose we need to iterate through all dog names in the dogs collection. Let’s do it from mongo shell.

1
2
3
4
5
6
7
8
> db.dogs.find().forEach( function(dog) {print("name: " + dog.name)})
name: Tyson
name: Rambo
name: Lala
name: Joyi
name: Scooby
name: Max
>

Observe the mongo shell command.

1
2
3
db.dogs.find().forEach(function(dog) {
  print("name: " + dog.name);
});

We used the find method to get all the documents and then used the forEach method with it. What exactly does the forEach method do? The forEach method takes a function as a parameter. The parameter passed in that function is the document through which the forEach method is currently iterating. A document is basically an object, so we can use it in the body of the function. In the command we used above, we print the name of each dog.

1
print("name: " + dog.name)}

We can specify any operation in the function body. Let’s try the if statement in the function body.

1
2
3
4
> db.dogs.find().forEach( function(dog) { if(dog.breed == "German Shephard"){ print("name: " + dog.name + "; gender: " + dog.gender)}})
name: Rambo; gender: Male
name: Lala; gender: Female
>

We used the if statement to filter the result. The output only contains data of the dogs whose breed is German Shephard.

map

Similar to the forEach method, the map method is also used to iterate through the documents of a collection. Everything is similar to the forEach method with a little exception. The map method returns an array of values. Let’s try the same iteration of documents in the dog collection.

1
2
3
> db.dogs.find().map( function(dog) {return dog.name})
[ "Tyson", "Rambo", "Lala", "Joyi", "Scooby", "Max" ]
>

The above command returns an array containing names of all the dogs. We can also print data in the function body but we have to return something, or else it will give an array full of undefined values.

1
2
3
4
5
6
7
8
9
> db.dogs.find().map( function(dog) {print(dog.name)})
Tyson
Rambo
Lala
Joyi
Scooby
Max
[ undefined, undefined, undefined, undefined, undefined, undefined ]
>

In the above command, we did not return anything from the function but printed the name of each dog. The result at the end has an array of undefined values. This is because the map method always returns an array.

Conclusion

The iteration is always useful when it comes to programming and developing. MongoDB also provides few iteration methods. In this article, we discussed the best two ways to iterate the mongoDb documents, the forEach and map method.

Pilot the ObjectRocket Platform Free!

Try Fully-Managed CockroachDB, Elasticsearch, MongoDB, PostgreSQL (Beta) or Redis.

Get Started

Keep in the know!

Subscribe to our emails and we’ll let you know what’s going on at ObjectRocket. We hate spam and make it easy to unsubscribe.