MongoDB Query Detailed

Source: Internet
Author: User
Tags findone mongodb query table definition

Query the first document that meets the criteria (cannot be called a record for MONGO)
Db. Collection_name.findone ({},{});

Query for eligible documents and sort by specified criteria, skip the previous N1 documents, and return a list of up to N2 documents
Sort skip limit three functions optional
Db. Collection_name.find ({},{}). The sort ({}). Skip (N1). Limit (N2);

Number of documents returning a condition
Db. Collection_name.count ({});

The above three lines of code are all of the query statements in the MONGO world.
FindOne Find count sort parameters are enclosed in curly braces. In terms of MONGO, their parameters are also a document, and it is worth mentioning that in the MONGO world, function parameters are the basic type if they are not documents. In the query-related parameters, skip and limit are integers as parameters, and some functions such as renaming collections, creating collections, initializing and managing shards, and so on are string parameters. Most of the other function parameters are passed in document form.

The first argument to find and FindOne is the query condition, and the second parameter specifies which fields in those documents that return the rule query criteria, and the second argument can be omitted.
The MONGO document is also a JSON object. But these are the documents that function as arguments, and their property names have special meanings.

The first parameter of find and FindOne:
The property name of the first parameter is the name of the property within the document to be queried, and the value of the property is the query condition for that property name.
Suppose we have the following databases:
Use TEST;
Db.createcollection (' USER ');
Db. User.findone ({name: ' Tom ', Password: ' passkey '});
This line of code will query the property name from the collection user with name and password, and the value is the first document of ' Tom ' and ' passkey ', respectively

The property value of a query parameter if it is a value of a simple type, MONGO will treat the query criteria as equals above. More complex queries will be presented in subsequent articles.
The FindOne call above will return all properties of the document that match the criteria, and if we only need a subset of the attributes in the document, then the second parameter of the query function comes in handy.
Db. User.findone ({name: ' Tom ', Password: ' passkey '},{name:1,registtime:1});
This line of code will still hit the same document within the database, but will not return all of the properties of the hit document, but only the name and Registtime properties.
As mentioned earlier, MONGO is not a strict database, that is, documents within the same collection do not necessarily have the same attributes, some documents may contain more attributes, and properties of the same name may be different data types in different documents.

If there is a part of the user collection of old data is not registtime, later due to changes in demand for new users have increased registtime.
If it is in a relational database, it is certain that all records have an registtime field added, and that the data table definition must be modified first. But now is the world of MONGO. We can modify the code of the program at any time when the requirements change, without having to explicitly modify the definition of the database schema. This will inevitably result in a part of the same data set that has no new fields in the old data. In this case, what will be handled by those documents that are not registtime and meet the query criteria? The answer is that these documents will still be returned, and if there is registtime in the document, return to Registtime, and not return if not. In other words, if you consider a document property name in a database as a mathematical set, the property name of the second parameter of the find* function is another collection, and the document property name in the returned result set is the intersection of the previous two sets.

The two parameters of the Find function are exactly the same as FindOne. It's not much to say.

It is worth mentioning that unless _id:0 is explicitly specified in the second parameter of the find* function, the _id property is included in the result set by default.

parameter of sort
As the name implies, it is sorted against the hit document.
Its parameter is a document. The document property name is the property to sort, the value of the property can be only 1 or -1,1 for ascending, and 1 for descending.

Skip (N1)
It skips the first N1 of the result set, but it still scans the N1 document, so skip is inefficient.
To ensure efficiency, you should make the results as small as possible before calling Skip.
The best practice is to specify the attributes in the first parameter document of the Find function, which, like the properties in the parameter document of the sort function, specifies that the documents that return the values of those properties larger than the maximum of the previous page are specified, and the document that returns them less than the minimum value of the previous page is specified instead. Replace skip in this way.

Limit (N2)
This is the last function called in the query statement, meaning to return at most N2 documents inside the hit result set.

A comparison of complex query conditions such as greater than, less than, existence, and null values will be presented in the next article.
MONGO's query conditions even support regular expression queries, which can embed JavaScript code in query statements, support query conditions for nested subdocument and array indexes, and so on. It can also create indexes on nested subforms and arrays.


The above mentioned queries are equivalent conditional queries, but we need more time to fuzzy query, non-equivalence query, pattern matching and so on. MONGO is not key-value storage, it supports very flexible and complex query methods, even more flexible than RDBMS, of course, more complex.

In addition, it needs to be said that NoSQL classification of these databases is not accurate, but RDBMS are all SQL, and they are not SQL, so they use NoSQL to classify these databases. In fact, technically, it is possible to implement a non-RDBMS and continue to use all the features of SQL to manipulate and manage the database. Of course, for ease of expression, this series of articles still use nosql as an inaccurate noun.

Since there is no SQL, it is natural to use other methods to operate the MONGO. The previous article has already appeared some, is uses the MONGO definition database operation API with its document form the operation parameter to complete the database creation, the modification, the deletion as well as the data delete and amend.

About the parameters of the query in the previous article almost finished, the remaining is the first parameter of find* and count.
Because the first parameter of find* is the same as the Count parameter, this article only describes the find function.

Querying a field is smaller than the specified value: $LT
Suppose there is a collection USERdb.USER.find ({regist_date:{$lt: New DATE (2013,0,1)}});
/* mentioned earlier that MONGO fully complies with JavaScript syntax, in JavaScript, the month is starting from 0, that is, the query above is a query for users registered before 2013-1-1. */
Querying a field is larger than the specified value: $GT
Db. User.find ({regist_date:{$gt: New DATE (2013,0,1)}});
/* $lt means less than the nature of the greater is $GT */
Greater than or equal to: $gte less than or equal to: $lte
Db. User.find ({regist_date:{$gte: new Date (2013,0,1), $lte: new Date (2013,0,31)}});
/* There seems to be some awkward questions about this time, no way, MONGO. Habit is good. */
/* The above line of queries is a combination query for Regist_date, indicating that all users registered from 2013-1-1 to 2013-1-31 are queried */

The next query method is more complicated.
Regular expressions, MONGO do not have similar SQL-like features, but you can use regular expressions instead
There are two cases of using regular expression queries, where regular expression literals, such as Ruby Nodejs, can be used directly in languages that support regular expression literals (scalars).
Db. User.find ({name:/^run/i});//In JavaScript, for example, this query out all users whose names start with run and are not case-sensitive
What about a language like Java that doesn't support regular expression scalars? It's a bit of a hassle, you need to use the MONGO API to complete conversions from string to regular expressions.
Db. User.find (name:{$regex: ' ^run ', $options: ' I '});//This line of command completes the same work as the previous line.
Where $options is the option of a regular expression, which has an optional combination of three letters, the three letters are G i m, these three letters can be arbitrarily combined to express different meanings.
G: Indicates that a match is made for the entire string, and returns if no regular expression is matched to the first conforming substring. (global)
I: Ignore case (insenssitive)
M: If a newline character exists within a string, it will be matched as a multiline pattern (multiple)
Two options other than I I'm afraid I can't use it in the query.
$in---Equivalent to SQL in, which can take advantage of the index
Db. User.find (name:{$in: [' Tom ', ' Jerry ']});
/* If an index is created for the Name field, it will look up from the index */
/*mongo are case-sensitive, so the names of collections and document properties must be the same as when they were created. */
/* Also name and name are two different properties that can exist in a document at the same time */
/* Within a collection if there is a document with the Name property and there is a document with the name attribute, the above command does not query the Name property.
$nin the opposite of---$in, the equivalent of SQL
Db. User.find (name:{$nin: [' Tom ', ' Jerry ']});
Note: $nin does not take advantage of the index, which means that the above command $nin does not use the index for the Name property.
$all---There is no analogous analogy to SQL, it means that the query condition is a simple value array, only the document that returns the property that satisfies all the values in the array. This query condition is only possible if the property value is an array.
Take my blog post for example. To find out all the documents that contain both NoSQL and MONGO tags, you can do this.
Assuming that Iteye is migrating the database to MONGO, the data model for the blog post can be defined like this
First, define a collection named blog.
This blog can be stored in the following ways
{
A _id:objectid (...), A.
Subject: ' MONGO profile--inquiry (continued) ',
Category: ' Database ',
user_category:[' NoSQL ', ' MONGO ',
Content: ' ... '... ',
tags:[' NoSQL ', ' MONGO ',
Origrinal:true,
Pub: ' Blog '
}
/*origrinal Indicates whether it is original; because there is no attachment, the document does not contain attachment properties, because I do not know how iteye define the channel, I use a string to represent the */
Below if you want to query all posts that contain ' nosql ' tags
Db.blog.find (Tags: ' nosql ');//This will do it.
Here's a look at the blogs that contain both ' nosql ' and ' MONGO ' tags
Db.blog.find (tags:{$all: [' NoSQL ', ' MONGO ']});
If some of the posts contain ' nosql ' and ' MONGO ' tags, they also include ' MONGO ' MONGO ' MongoDB ' MongoDB ' NoSQL ' and the above command will be returned together.
What if I don't want to use a regular expression to do a fuzzy match if I want to ignore the case of the query?
The answer is no.
This requirement is still common, so the only way to do this is when the user saves the blog post, the program finds similar words based on previously existing tags and automatically creates several different case-sensitive tags that might appear. For example, when I save this article, the program automatically creates the above-mentioned few tags that I didn't specify.
$ne---Inequality comparison, it receives a single value or an array
Db.blog.find (tags:{$ne: ' NoSQL '});//return all posts that do not contain nosql tags
Db.blog.find (tags:{$ne: [' NoSQL ', ' MONGO '});//return all posts that do not contain both the NoSQL and MONGO tags
$size---Check the size of an array, do not use the index, can not do the scope of the query, you may increase this support in the future
Sometimes Iteye will express some prizes to the user, Iteye may save the address that the user has filled in. You can save this.
Add an address attribute to the user collection without having to leave any addresses.
A user does not have to have only one address, this address can be created as an array of strings.
For example, to return all users who have only one address left.
Db. User.find (address:{$size: 1});
Sometimes, if Iteye want to know more about the user's address information, they need to save the address with a more complex document. Like what:
{
The _id:objectid (...),
AccountName: ' Runfriends ',
Address:[{category: ' Home ', City: ' Beijing ', District: ' Dongcheng ', street: ' ... ',
{category: ' Company ', City: ' Beijing ', District: ' Haidian ', street: ' ... '}]
}
If you want to find out all the users in Beijing, how to do it?
May be written like this:
Db. User.find ({' address.category ': ' Home ', ' address.city ': ' Beijing '}).
But this is wrong! The meaning of this line of command is to query out all the addresses within the category containing home, and the address of the city contains users of Beijing. Some users have their company address in Beijing, and the home address is not, and these users will be matched to.
Then we're going to use the $elemmatch.
It is only used if you need to match multiple properties of a subdocument
Db. User.find (address:{$elemMatch: {category: ' Home ', City: ' Beijing '}});
$not---The inverse value, which is required only if the opposite action is not specified. Because most operators have opposite operations, you should try to use the opposite operator, such as regular expression matching, without the opposite action
If one day, Iteye only allows the user name to start with a letter can be all the users do not start with the letter to find out to send them an e-mail, let them rename.
Db. User.find (accountname:{$not:/^[a-za-z]/})
Of course $not also receives a single value, but it is not recommended
$exists----Check the existence of a property.
For example, all the posts that contain attachments are queried.
Db.blog.find ({attachment:{$exists: true});
No attachment is Db.blog.find ({attachment:{$exists: false}});
Or you can do this:
Db.log.find ({attachment:null});//does not exist
Db.blog.find ({attachment:{$ne: null}});//Exists
The previous introduction of Bson said that null value uses nil, but here is null, because nil is the definition of Bson, here is the syntax of JavaScript
$mod-----To find the remainder without using the index
If said one day Iteye whim to give all ages can be 4 whole team of users express a prize.
Db. User.find ({age:{$mod: [4,0]}});//The first value of the array is a divisor, the second value is the desired remainder
$type---query by property type
Although it is not recommended that different types of data be stored in the same property names for different documents in the same collection, this can sometimes occur because of a program bug or a lack of design rigor. Now it's time to find out, for example, the _id attribute has some objectid types, and there are integers. Here's a look at all the documents that _id are strings.
Db. User.find (_id:{$type: 2})
Db. User.find (_id:{$not: {$type: 7}});//Find all primary key Objectid type documents
$or $and----Logical operation
Their meaning is not much to explain. But they're very interesting to use.
For example, to find all the monthly income of more than 20000 or less than 2000 users
Db. User.find ({$or: [{salary:{$gt: 20000}},{salary:{$lt: 2000}]});
Find all monthly income of over 8000, 20000 users below
Db. User.find ({$and: [{salary:{$gte: 8000}},{salary:{$lte: 20000}]});
Querying nested documents and array elements
The preceding content has a brief look at some of the queries for nested documents and array elements. queries for nested documents and arrays follow the same syntax rules
1. They all use the dot number to split the properties of the nested document, and if the index of the array is represented by a number starting from 0.
Db. User.find ({' address.category ': ' Home ');//This is to find all the users who have left their home address
If you want to know if the user left the first address is not a home address can do this:
Db. User.find ({' address.0.category ': ' Home '});
What if you want to return only the user who left the home address and return only the home address without returning to another address?
I'm afraid I can't do that with the data model I'm using now, but I'm afraid I can only define different fields for different addresses if I have this kind of demand.
Of course, if the code specification specifies that the first address must be a home address, you can do this:
Db. User.find ({' address.0.category ': ' Home '},{' accountname ': 1, ' address.0 ': 1});
Usually, however, it is better to define the first address as the default address.
$where-----Receive a piece of JavaScript code as a query condition without using the index
If you want to query all users born in leap years
Db. User.find ({$where: ' var year=birthday.getfullyear (); return year%4==0 && year%100>0 | | year%400==0 ';});
Or:
Db. User.find ($where: ' function () {var year=this.birthday.getfullyear (); return year%4==0 && year%100>0 | | year% 400==0 '} ');

Well, there are so many ways to query about MONGO.

MongoDB Query Detailed

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.