NoSQL Top

Build a Dashboard Using Cassandra, Astra, and Stargate:

>> CHECK OUT THE ARTICLE
Persistence top

Get started with Spring Data JPA through the reference Learn Spring Data JPA course:

>> CHECK OUT THE COURSE

1. Overview

In this tutorial, we'll learn how to retrieve a value from MongoDB by key name. We'll explore various methods of MongoDB, to fetch the key field names of the documents based on applied filters. First, we'll use the find or findone method to fetch the required data and later use the aggregation method. Here, we'll write queries both in the MongoDB shell query and Java driver code.

Let's look at the different ways to retrieve the value in MongoDB by a field name.

2. Database Initialization

To begin, we need to set up a new database baeldung and a new collection, travel:

use baeldung;
db.createCollection(travel);

Let's now add some dummy data into the collection using the insertMany method of MongoDB:

db.travel.insertMany([
{ 
    "passengerId":145,
    "passengerName":"Nathan Green",
    "passengerAge":25,
    "sourceStation":"London",
    "destinationStation":"Birmingham",
    "seatType":"Slepper",
    "emailAddress":"[email protected]"
},
{ 
    "passengerId":148,
    "passengerName":"Kevin Joseph",
    "passengerAge":28,
    "sourceStation":"Manchester",
    "destinationStation":"London",
    "seatType":"Slepper",
    "emailAddress":"[email protected]"
},
{ 
    "passengerId":154,
    "passengerName":"Sheldon burns",
    "passengerAge":26,
    "sourceStation":"Cambridge",
    "destinationStation":"Leeds",
    "seatType":"Slepper",
    "emailAddress":"[email protected]"
},
{ 
    "passengerId":168,
    "passengerName":"Jack Ferguson",
    "passengerAge":24,
    "sourceStation":"Cardiff",
    "destinationStation":"Coventry",
    "seatType":"Slepper",
    "emailAddress":"[email protected]"
}
]);

The above insertMany query will return the following JSON:

{
    "acknowledged" : true,
    "insertedIds" : [
        ObjectId("623d7f079d55d4e137e47825"),
	ObjectId("623d7f079d55d4e137e47826"),
	ObjectId("623d7f079d55d4e137e47827"),
        ObjectId("623d7f079d55d4e137e47828")
    ]
}

Till now, we have inserted the dummy data into the collection travel.

3. Using the find Method

The find method finds and returns documents that match the specified query criteria on the collection. If multiple documents match the condition, then it'll return all the documents based on the order of documents on the disk. Additionally, in MongoDB, the find method supports parameter projection in the query. If we specify a projection parameter in the find method, it'll return all documents containing only projection fields.

One key point to note is that the _id field is always included in the response unless explicitly removed.

To demonstrate, let's look into the shell query to project a key field:

db.travel.find({},{"passengerId":1}).pretty();

The response to the above query will be:

{ "_id" : ObjectId("623d7f079d55d4e137e47825"), "passengerId" : 145 }
{ "_id" : ObjectId("623d7f079d55d4e137e47826"), "passengerId" : 148 }
{ "_id" : ObjectId("623d7f079d55d4e137e47827"), "passengerId" : 154 }
{ "_id" : ObjectId("623d7f079d55d4e137e47828"), "passengerId" : 168 }

Here, in this query, we simply projected the passengerId. Let's now look into the key field with the exclusion of _id:

db.travel.find({},{"passengerId":1,"_id":0}).pretty();

The above query will have the following response:

{ "passengerId" : 145 }
{ "passengerId" : 148 }
{ "passengerId" : 154 }
{ "passengerId" : 168 }

Here, in this query, we excluded the _id field from the response projection. Let's see the Java driver code for the above query:

MongoClient mongoClient = new MongoClient("localhost", 27017);
DB database = mongoClient.getDB("baeldung");
DBCollection collection = database.getCollection("travel");
BasicDBObject queryFilter = new BasicDBObject();
BasicDBObject projection = new BasicDBObject();
projection.put("passengerId", 1);
projection.put("_id", 0);
DBCursor dbCursor = collection.find(queryFilter, projection);
while (dbCursor.hasNext()) {
    System.out.println(dbCursor.next());
}

In the above code, first, we created a MongoClient connection with the local mongo server running on port 27017. Next, we used the find method, which has two parameters, the queryFilter, and projection. The query DBObject contains the filters on which we need to fetch the data. Here we printed all the projected fields of travel documents using the DBCursor.

4. Using the aggregation Method

The aggregation operations in MongoDB process data records and documents and return computed results. It collects values from various documents and groups them together before performing different types of operations on the grouped data, such as sum, average, minimum, maximum, etc.

We can use the MongoDB aggregation pipeline when we need to do more complex aggregation. Aggregation pipelines are collections of stages combined with MongoDB query syntax to yield aggregated results.

Let's look into the aggregation query to retrieve the value by key name:

db.travel.aggregate([
{
    "$project":{
        "passengerId":1
    }
}
]).pretty();

The response to the above aggregation query will be:

{ "_id" : ObjectId("623d7f079d55d4e137e47825"), "passengerId" : 145 }
{ "_id" : ObjectId("623d7f079d55d4e137e47826"), "passengerId" : 148 }
{ "_id" : ObjectId("623d7f079d55d4e137e47827"), "passengerId" : 154 }
{ "_id" : ObjectId("623d7f079d55d4e137e47828"), "passengerId" : 168 }

In this case, we used the $project stage of the aggregation pipeline. $project specifies what fields to include or exclude. In our query, we only passed the passengerId into the projection stage.

Let's look at the Java driver code for the above query:

ArrayList<Document> response = new ArrayList<>();
ArrayList<Document> pipeline = new ArrayList<>(Arrays.asList(new Document("$project", new Document("passengerId", 1L))));
database = mongoClient.getDatabase("baeldung");
database.getCollection("travel").aggregate(pipeline).allowDiskUse(true).into(response);
System.out.println("response:- " + response);

We can also write the aggregation pipeline in the following way:

ArrayList<Document> response = new ArrayList<>();
ArrayList<Bson> pipeline = new ArrayList<>(Arrays.asList(
  project(fields(Projections.exclude("_id"), Projections.include("passengerId")))));
MongoDatabase database = mongoClient.getDatabase("baeldung");
database.getCollection("travel").aggregate(pipeline).allowDiskUse(true).into(response);
System.out.println("response:- "+response);

We created an aggregation pipeline with the java driver code and set the project stage only to include the passengerId field. Finally, we passed the aggregation pipeline to the aggregate method to retrieve the data.

5. Conclusion

In this article, we learned to retrieve the value by key name in MongoDB. We explored different methods of MongoDB to fetch the data. First, we retrieve the data using the find method and then the aggregate method. We looked into the use cases of the projection of fields in MongoDB. In short, we implemented the projection of fields using Mongo shell query and Java driver code.

We can find the implementation of all the cases over on GitHub.

NoSql Bottom

Build a Dashboard Using Cassandra, Astra, and Stargate

>> CHECK OUT THE ARTICLE
Persistence bottom
Get started with Spring Data JPA through the reference Learn Spring Data JPA course: >> CHECK OUT THE COURSE
Persistence footer banner
Comments are closed on this article!