MongoDB Queries and Projections

Utilising queries and projections shrewdly on the server can spare your customers a considerable measure of pointless overhead.

0 47

In MongoDB, Projections are an approach to bring just the required fields of an archive from a database. This lessens the measure of information that must be exchanged from database server to customer and consequently expands execution.

If you are working with the data in Meteor applications, you must know the keynote that how to leverage MongoDB Queries Projections .Combination of these helps us to avoid unnecessary fields like extras and private data, also keeps the data selection more efficient. This safeguards the clients data from trimming down in some special cases.

Let’s discuss What are MongoDB Queries and Projections? Gain knowledge on simple high-level generalizations to MongoDB native query language and projections.

If you’re new to this topic, refer to our introductory article Getting Started With MongoDB And Python Tutorial.

MongoDB Queries:

In general MongoDB treats each property as having an implicit Boolean AND. For building a query, you must mention an document with all properties you wish as resulting output. For pulling the queries using MongoDB we can use different approaches.

The traditional approach is

MongoDB Queries:

  • Get data from MongoDB
  • Run it through a random library
  • Spill out a winner

Here are some major mongodb operators that be can used for ‘Greater / Less than’ conditions.

$gt — Greater than
$gte — Greater than or equal to
$lt — Less than
$lte — Less than or equal to

Let’s write the sample query document that match all documents in the user’s collection having the firstname “Mind”:

q  = {
   “firstname” : “Mind”
}

Let’s think, If we want to retrieve all documents by using the firstname “Mind” AND surname “Majix”, we would write:

q = {
   “firstname” : “Mind”,
   “surname” : “Majix”
}

The MongoDB query language offers numerous operators, that allow you to build complex queries. To make that a little clearer, here’s a diagram:

mongodb queries

In this example, we used the database selection name as users using the find collection method. In the first argument to our find method, we pass a Query document that contains the criteria for our search. At last, we have a Projection  that describes our find selection, “From database find username, when you return them, make sure they only have the firstname field.”

In the above example, collection names are very clear, so let’s look into the 3 tools that uses for retrieving the data from our collection: Methods, Queries, and Projections.

Using MongoDB Collection Methods for selection

Collection – A group of MongoDB documents. In Meteor, for database calls we have two methods:

  1. find( ): Returns a multiple documents, while method is actually returning a cursor to the documents so called as as MongoDB Cursor
  2. findone( ): Return single document.

The find() method: For finding the documents that match a set of collection criteria, you can call find() method with the <criteria> attribute. Depending on the query and the projection that we pass to our collection method, the above operation returns all the documents from the database collection products where username is greater than 0 value. For example, the following operation returns all documents in the users collection:

db.users.find()

MongoDB Collection Methods

 

The findOne() method:

This returns single document that meets the criteria specified as the first argument to this method. If you want MongoDB: db.collection.findOne() method with a Query specification then it returns the first matching document from users collection, where either the firstname in the document starts with the word “Mind” the username in the embedded document address is more than 0.

 

findOne

 

If you wanted to find all documents using multiple fields

In case, MongoDB queries can pass multiple fields. This implies we can have boundlessly complex queries that makes it extremely decent to look up data in collections. Suppose if we had the accompanying collection of documents:

find all documents using multiple fields

 

And the below query:

Documents.find( { "user": "1162", "category": "recipes", "date.year": 2018 } );


Yeah! In this illustration, we can see our inquiry is going up against three fields. Here, we’re stating “give me the greater part of the archives where the user field (some client) is equivalent to the ID 1162, the report is in the category ‘recipes’, and the publication year date.year is 2018.”

In view of our query above, we should just get two of these records came back to us.

Note: These archives are claimed by a similar user, but since their categories and years distributed shift, we’ll just get back the one’s our query has determined.

 

 

Advanced querying

This is all cool, but we can go even further.

Let’s setup some example documents and then write an advanced query to pick only the documents that we want.

 

 

We just need to get two documents out of this set: the one’s the place the proprietor is “1162”, category is “photographs” or “announcements”, the year distributed is before 2018, and where the tags are equivalent to “baby” and “wedding”. This is a considerable measure of stuff, however there’s some uplifting news: we can do this with a solitary query.

 

 

On the off chance that we’ve done our activity well, we ought to get back this outcome set:

In the first place, we get the greater part of the documents where the owner field matches “1162”. Simple. Next, we utilize the MongoDB $in Operator to state, “give every one of us of the records where the estimation of category is equivalent to one of the qualities in this exhibit we’re passing.

Next, we thin our query around saying give all of us of the documents where the estimation of date.year is under 2018, utilizing the MongoDB $lt Operator.

At long last, we utilize the $in administrator again to watch that our tags field has baby or wedding in it (yes, $in attempts to check whether the qualities in the exhibit we’ve passed are in a cluster set to that field).

Isn’t that cool?! With a solitary query, we figured out how to get hyper-particular with what we needed in an accumulation.

Considerably all the more energizing is this is only a hint of a greater challenge.

We approach various operators in MongoDB that can enable us to whittle down our list items.
Okay. That was truly wild, however now that we know how to choose records, how about we perceive how we can additionally trim down the outcomes we get utilizing projections.

In MongoDB, Projections are an approach to bring just the required fields of an archive from a database. This lessens the measure of information that must be exchanged from database server to customer and consequently expands execution.

With Spring Data MongDB, projections can be utilised both with MongoTemplate and MongoRepository.

Before we move further, how about we take a gander at the information demonstrate we will utilize:

 

When you are using MongoDB Queries and Projections to expel unused fields, the MongoDB server should bring each full record into memory (on the off chance that it isn’t as of now there) and filter the outcomes to return. This utilisation of projection doesn’t lessen the memory use or working set on the MongoDB server, however can spare noteworthy system transfer speed for inquiry comes about relying upon your information demonstrate and the fields projected.

In the second contention / argument go to our gathering technique we can characterise something known as a projection document. That name is a little squirrly, yet fundamentally this document enables us to state

“given the outcomes that you found with our inquiry, how about we take that outcome set and channel it further.”

Cool! Once more, code is least demanding here. Allows piggyback on our last illustration we utilised while taking a gander at how to characterise progressed MongoDB Queries.
Once more, we have this huge document sets and just need to get two back.

 

// Our whole document set.

 

 

// The result we got using this query.

 

 

How about we change the query we used to restore those last two documents a bit. At the present time, we’re getting back the greater part of the fields in that document. Imagine a scenario in which we just needed to get the title of the documents that match this query.

 

For correlation, here’s the aftereffect of our question before we include this projection, and after that after:

// Before we added our projection.

// After we add our project.

 

 

Woah. The utility in this may not be totally clear. Let’s assume we had a piece of our interface where a client could flip a few channels. Those filters enabled us to create a query like the one above (searching for classification, year distributed, and so forth). When we go to yield the rundown of posts that match that query, as an developer, we realize that with a specific end goal to show a rundown of presents back on user, we just need the _id of that report (to connection to) and its title.

In any case, wait…where did that _id originate from?

The _id field is constantly returned except if indicated.

By outline, except if we explicitly pass { fields: { “_id”: 0 } to our query, we will dependably get back a _id field.

We can take this case much further simply like our questions and pass numerous projection activities to get as particular as could be allowed:

 

 

 

Presently, we recover our outcome sorted by the title chronological order:

Really insane. However, wait…what is this 1 and -1 stuff about? As a matter of fact, this is quite confounding at first.

In our fields projection, 1 is equivalent to true. In Mongo-speak, this implies it’s “true” that we should just send back the title field. Give that splash access. If we somehow happened to change this to a 0, or false, we’d be stating “send back everything in this document yet the title field.”

The last sort setting title to a -1 is pure witchcraft with respect to MongoDB. As clarified in the documentation for sort:

Determine in the sort parameter the field or fields to sort by and an estimation of 1 or -1 to indicate a ascending or descending sort individually – via MongoDB Sort Documentation.

In this way, on the off chance that we set a field to 1, that implies that we’ll get back our outcome set arranged by that field in ascending request (1 1 6 2). In the event that we change that to – 1, we get our outcome set arranged by that field in descending request (2 6 1 1 ).

Once more, much the same as our queries, there are many kinds of projections that we can go in Meteor keeping in mind the end goal to channel our outcomes.

Using Queries and Projections

While we’ve disclosed how to utilize queries and projections in a general sense in this bit, we haven’t generally discussed where they’re best connected. The majority of the code we’ve seen here can be connected on the customer and the server.

As a general rule, however, queries and projections are most appropriate for use on the server, and all the more particularly, inside your distributions. The explanation behind that needs to do with the idea of distributions and how they control what information gets to the customer from the server. Think about your distribution as the strainer for your information. It goes about as the mediator between the customer and the server in regard to your information, restricting what really gets sent to the customer.

It’s best to apply the methods we’ve delineated above before your information hits the customer. Why? Since this will guarantee that we’re just sending the customer what it truly needs at any given point in time. We could play out these same tasks on the customer, nonetheless, we’d being doing as such on a significantly bigger informational index that we needed to load our customer (read: user) with first.

Takeaways

  • When maneuvering data into your application, ponder what queries and projections you can use to thin down your outcome sets to just what you require.
  • Utilizing queries and projections shrewdly on the server can spare your customers a considerable measure of pointless overhead.
  • Make sure to consider whether a find() (whole cursor) or findOne() (single document) is important while querying information.

 

Author Bio:
Tejaswini UL: The author has an experience of more than 5+ years of corporate experience in various technology platforms such as Big Data, AWS, MongoDB, Data Science, Salesforce, Digital Marketing, CRM, SQL, JAVA, Oracle, etc. she is a technology nerd and loves contributing to various open platforms through blogging. she is currently in association with a leading professional training provider, Mindmajix Technologies. and strives to provide knowledge to aspirants and professionals through personal blogs, research, and innovative ideas.
Comments
Loading...

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More