📜 ⬆️ ⬇️

MongoDB: Requests

Although some have written about my previous MongoDB topic : Creating, updating and deleting documents , this is a retelling off. documentation, I do not fully agree. It seemed to me that the information in it turned out to be useful to someone, so I am posting a sequel.

Find - analog SELECT in MySQL. Used to fetch documents from MongoDB. Returns an array of documents in the form of a collection; if there are no documents, an empty collection. Example:

> db.users.find();

Will return all users from the collection.
')
> db.users.find( { age: 27 } );

Will return all users whose age is equal to 27.

You can specify several parameters, for example, like this:

> db.users.find( { username: “joe”, age: 27 } );

Sometimes it is necessary to get some specific fields from the documents. In this case, the query looks like this:

> db.users.find( { }, { username: 1, email: 1 } );

As a result, we get all users with only the fields “username” and “email” + the field “_id”, which is always returned by default. If the field "_id" or any other is not needed, we can indicate it like this:

> db.users.find( { }, { username: 1, email: 1, _id: 0 } );

Requests with condition



Operators: $ lt - less, $ lte - less or equal, $ gt - more, $ gte - more or equal, $ ne - not equal.
Examples of using:
We get all users whose age is more than 18 and less than 30

> db.users.find( { age: { $gte: 18, $lte: 30 } } );

We get all users whose username is not equal to “joe”

> db.users.find( { username: { $ne: “joe” } } );

Suppose we have a collection that holds lottery tickets with numbers and we need to find only those with winning numbers 390, 754, 454. In this case, we use the $ in operator:

> db.users.find( { numbers: { $in: [ 390, 754, 454 ] } } );

those. ticket must contain one of these numbers.
The opposite of the $ in operator is $ nin. He, by analogy, receives only those tickets where there are no, the above numbers.
The $ or operator is used in queries when you need to select documents by coincidence one of the values. For example, we need to select all tickets with number 547 or where the "winner" field is true:

> db.users.find( { $or: [ { tickect_number: 547 }, { winner: true } ] } );

The $ mod operator is used to select keys whose values ​​are divided by the first argument and the remainder of the division is equal to the second argument. It sounds incomprehensible, here's more clearly:

> db.users.find( { user_id: { $mod: [ 5, 1 ] } } );

Such a request will return all users whose “user_id” is 1, 6, 11, 16, and so on.
To get all users except the above, you can use the $ not operator:

> db.users.find( { user_id: { $not: { $mod: [ 5, 1 ] } } } );

We will get users with "user_id" 2, 3, 4, 5, 7, 8, 9, 10, 12 and so on.
There is also an operator to check if there is any key or not - $ exist

> db.c.find({"z" : {"$in" : [null], "$exists" : true}});

So you can select all the documents in the collection where the key “z” exists and it is null.

Regular expressions



We all know that regular expressions are very powerful stuff. MongoDB uses Perl-compatible regular expressions.
This is how you can find all users with the name joe or Joe:

> db.users.find( { "name" : /^joe$/i } );

In general, there is where to roam. There are a lot of services for the same javascript, where you can write and check your regulars.

Queries in arrays



Suppose we have a collection of food and we insert a document with an array of fruits

> db.food.insert( { "fruit" : [ "apple", "banana", "peach" ] } );

That such request

> db.food.find({"fruit" : "banana"});

successfully find him.
If you need to select documents more than one element of the array, then we can use the operator $ all

> db.food.find( { fruits: { $all : [ "apple", "banana" ] } } );

Such a request will return all documents in the fruit array of which there are both apples and bananas.
We can get documents on the complete coincidence of elements in an array like this:

> db.food.find( { fruits: [ "apple", "banana", "peach" ] } );

We have a blog, it stores comments. We want to get the first 10 comments. The $ slice operator comes to the rescue:

> db.blog.posts.findOne( { }, { "comments" : { "$slice" : 10 } } );

findOne - works like find, but returns the first matched document.

If you need to get the last 10 comments, we write this:

> db.blog.posts.findOne( { }, { "comments" : { "$slice" : -10 } } );

Also $ slice can get documents from the middle:

> db.blog.posts.findOne( { }, { comments : { "$slice" : [ 23, 10 ] } });

in this case, 23 initial elements will be skipped and elements from 24 to 34 will return, if possible

Commands limit, skip and sort



In order to get a limited number of documents on request, use the limit command:

> db.users.find().limit(3);

Will return the first 3 users.
In order to skip several documents and get all the rest, use the skip command:

> db.users.find().skip(3);

We get all users except the first three.
For sorting, use the sort command. Sorting can be ascending (1) and descending (- 1). Sorting can be performed on several keys in the order of their priority:

> db.users.find().sort( { username : 1, age : -1 } );

All these three commands can be used together:

> db.stock.find( { "desc" : "mp3" } ).limit(50).skip(50).sort( { "price" : -1 } );

Using the skip command with large values ​​does not work very fast. Consider this on the example of pagination:

The easiest way to do pagination is to return the fixed number of documents for the first time, and then each time shift the range by this value.

> var page1 = db.foo.find(criteria).limit(100)
> var page2 = db.foo.find(criteria).skip(100).limit(100)
> var page3 = db.foo.find(criteria).skip(200).limit(100)


but it will work rather slowly. Suppose we will do a sample with respect to the date the document was created:

> var page1 = db.foo.find().sort( {"date" : -1} ).limit(100);

Sort in descending order and take the first 100. In order not to skip, we can get the date of the last document and make a request for this date:

var page2 = db.foo.find( { "date" : { "$gt" : latest.date } } );

This avoids using the skip command for large values.

In fact, these are basic things about requests in MongoDB. I hope it will be useful to someone.

Source: https://habr.com/ru/post/134590/


All Articles