Querying data in the MongoDB database (bottom)

Source: Internet
Author: User
Tags findone mongodb

Querying data in the MongoDB database (bottom)

In Find, the option parameter value is an object that sets the options used when querying data, and we describe the properties that can be used in this parameter value object:

1. Fields; The property value is an object in which the property names are used to display fields that you specify to include or exclude in the query results. The property value can be 1 or 0, and when the property value is 1 o'clock, the representation needs to include the field in the query results, and when the property value is 0 o'clock, the field is excluded from the query results.
Note: When you use the Fields property, you need to uniformly use the attribute value 1 or the attribute value of the _id field to set all but the field.

Let's start by looking at what data is in the database, as follows:

Below we use the fields field to include or exclude from the query results, the following is a field specified in the query result that contains only userName: ' Lone ' (the _id field is also included by default when the _id field is not specified separately);

Collection.find ({userName: ' lone '},{fields: {username:1}});

All codes are as follows:

Const MONGO = require (' MongoDB '); Const Server=MONGO. Server;const Db=MONGO. Db;const Server=NewServer (' localhost ', ' 27017 ', {auto_reconnect:true}); Const DB=NewDb (' datadb ', server, {safe:true});d B.open (function(err, db) {if(err) {Throwerr; } Else{Console.log (' Successfully established database connection '); Db.collection (' Users ',function(Err, collection) {if(err) {Throwerr; } Else {        //Start Query Collection usersCollection.find ({userName: ' lone '},{fields: {username:1}}). ToArray (function(Err, docs) {if(err) {Throwerr; } Else{console.log (docs);          Db.close ();      }        });  }    }); }});

As shown in the following:

We can specify separately whether the _id field needs to be included or deleted, as follows: We specify the exclude _id field in the query results, as follows.

Collection.find ({userName: ' Empty Intelligence '}, {fields: {username:1, _id:0}});

All codes are as follows:

Const MONGO = require (' MongoDB '); Const Server=MONGO. Server;const Db=MONGO. Db;const Server=NewServer (' localhost ', ' 27017 ', {auto_reconnect:true}); Const DB=NewDb (' datadb ', server, {safe:true});d B.open (function(err, db) {if(err) {Throwerr; } Else{Console.log (' Successfully established database connection '); Db.collection (' Users ',function(Err, collection) {if(err) {Throwerr; } Else {        //Start Query Collection usersCollection.find ({userName: ' Empty Smart '}, {fields: {username:1, _id:0}}). ToArray (function(Err, docs) {if(err) {Throwerr; } Else{console.log (docs);          Db.close ();      }        });  }    }); }});

As shown in the following:

If you set some fields using the attribute values in the Field object, the query results will contain all fields except those fields.

We can first query username= "EMPTY wisdom" after this field, and then through fields to exclude userName This property value, so the code can be changed to the following:

Collection.find ({userName: ' Empty Intelligence '}, {fields: {username:0}});

All the code looks like this:

Const MONGO = require (' MongoDB '); Const Server=MONGO. Server;const Db=MONGO. Db;const Server=NewServer (' localhost ', ' 27017 ', {auto_reconnect:true}); Const DB=NewDb (' datadb ', server, {safe:true});d B.open (function(err, db) {if(err) {Throwerr; } Else{Console.log (' Successfully established database connection '); Db.collection (' Users ',function(Err, collection) {if(err) {Throwerr; } Else {        //Start Query Collection usersCollection.find ({userName: ' Empty Smart '}, {fields: {username:0}}). ToArray (function(Err, docs) {if(err) {Throwerr; } Else{console.log (docs);          Db.close ();      }        });  }    }); }});

As shown in the following:

2. Sort;
This property is the field that needs to be sorted, and the property value can be an array or an object.
2.1 The attribute value is in the case of an array:
When the property value is an array, the array contains two elements, the first element value is the field name used for sorting, the second element value can be 1 or-1, the element value is 1 o'clock to specify an ascending sort, and the element value is-1 when the specified descending sort. And each element is an array.
The following code is sorted in ascending order by the Type field, and the Price field is sorted in descending order; code is as follows:

collection.find ({},   {sort:       [        [' type ', 1],        [' Price ',-1]      ]    })

All the following code:

Const MONGO = require (' MongoDB '); Const Server=MONGO. Server;const Db=MONGO. Db;const Server=NewServer (' localhost ', ' 27017 ', {auto_reconnect:true}); Const DB=NewDb (' datadb ', server, {safe:true});d B.open (function(err, db) {if(err) {Throwerr; } Else{Console.log (' Successfully established database connection '); Db.collection (' Users ',function(Err, collection) {if(err) {Throwerr; } Else {        //Start Query Collection userscollection.find ({}, {sort: [[' Type ', 1],              [' Price ',-1]]}). ToArray (function(Err, docs) {if(err) {Throwerr; } Else{console.log (docs);          Db.close ();      }        });  }    }); }});

The query results are as follows:

2.2 When the property value is an object
When the Sort property value is an object, each property in the object is named for the field name used for sorting, each property value can be 1 or-1, the property value is 1 o'clock specifies an ascending sort, and the property value is-1 specifies a descending sort.
The following code is sorted in ascending order by the Type field, and the Price field is sorted in descending order; code is as follows:

Collection.find ({},{sort: {type:1, Price:-1}});

All the code is the same as above, just to change the query conditions, the results of the operation and the same as above. You can see that the property value is more simple than the array when the object is.

3. Limit
This property is to limit the number of query result bars, which is an integer that specifies the number of query result bars.

Now we're going to change the code of the query, and I'm now going to look at 2 of the data in username= ' empty intelligence ', as shown in the following code:

Collection.find ({userName: ' Empty Intelligence '}, {limit:2});

The execution results are as follows:

4. Skip
This property is a document that restricts how many previous data is skipped from the results that meet the query criteria, which is an integer that specifies the number of data document bars to skip.

First, let's look at the following data in the database, as follows:

Then we specify in the query results userName = ' empty intelligence ' field, the database has a total of 8 username= ' empty intelligence ' data, we now skip the previous 6, starting from seventh, the following code:

Collection.find ({userName: ' Empty Intelligence '}, {skip:6});

The results of the operation are as follows:

5. Explain
This property is to view detailed performance information when executing a Find method query data, and after using this property, the Find method does not actually perform a query operation on the data, which returns only performance information when querying the data. The following code:

true})

All codes are as follows:

Const MONGO = require (' MongoDB '); Const Server=MONGO. Server;const Db=MONGO. Db;const Server=NewServer (' localhost ', ' 27017 ', {auto_reconnect:true}); Const DB=NewDb (' datadb ', server, {safe:true});d B.open (function(err, db) {if(err) {Throwerr; } Else{Console.log (' Successfully established database connection '); Db.collection (' Users ',function(Err, collection) {if(err) {Throwerr; } Else {        //Start Query Collection usersCollection.find ({},{explain:true}). ToArray (function(Err, docs) {if(err) {Throwerr; } Else{console.log (docs);          Db.close ();      }        });  }    }); }});

As shown in the following:

6. Raw
The raw property in the parameter value object specifies whether the binary Bson data document is stored in the cache when querying data, and then returns the buffer as a query result. The following code:

true});

As shown in the following:

7. FindOne

The method is to query a data document from a collection that, by default, returns only the first data document when there are multiple data documents in a collection that meet the criteria of the query.
Use as follows:

Collection.findone (selector, [options], callback);

Selector is a query condition and must be filled in.
Options are the qualifying conditions for querying data.
Callback: Used to specify the callback function to execute at the end of the Get query data operation, as shown in this callback function:

function (Err, Docs) {}

The first parameter, err, is the error object that fires when a data operation fails, and the second parameter is the data document that is queried. The following code:

function (Err, Docs) {})

All codes are as follows:

Const MONGO = require (' MongoDB '); Const Server=MONGO. Server;const Db=MONGO. Db;const Server=NewServer (' localhost ', ' 27017 ', {auto_reconnect:true}); Const DB=NewDb (' datadb ', server, {safe:true});d B.open (function(err, db) {if(err) {Throwerr; } Else{Console.log (' Successfully established database connection '); Db.collection (' Users ',function(Err, collection) {if(err) {Throwerr; } Else {        //Start Query Collection usersCollection.findone ({},function(Err, docs) {if(err) {Throwerr; } Else{console.log (docs);          Db.close ();      }        });  }    }); }});

As shown in the following:

Querying data in the MongoDB database (bottom)

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.