Querying data in the MongoDB database (top)

Source: Internet
Author: User
Tags mongodb

Querying data in the MongoDB database (top)

In the MongoDB database, you can use the Find method of the collection object to query multiple data documents from a collection, using the Find method as follows:

Collection.find (selector, [options]);

The selector value is an object that specifies the query criteria to use when querying, and options is an optional parameter that is an object that specifies the options that are selected when querying data.

The Find method returns a Cursor object that represents the cursors in which all the queried data document information is contained. You can use the ToArray method of the cursor object to get all the queried data documents by using the following method:

Collection.find (selector, [options]). ToArray (callback);

The callback is used to specify a callback function that executes at the end of a data document operation, using the following example:

function (Err, Docs) {};

In the callback function, the Err parameter is the error object that is triggered when the data document operation fails, and the docs parameter is an array that contains all the data documents that were queried.

The following is a query for all data in the user union, if the query fails, the error object that fires when the query data fails is thrown, and if the query succeeds, output all the queried data in the console, and then close the database 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 ({}). ToArray (function(Err, docs) {if(err) {Throwerr; } Else{console.log (docs);          Db.close ();      }        });  }    }); }});

As shown in the following:

Second: Query the data according to the query criteria

2.1 You can specify the fields and field values in the query criteria that you want to query, as shown in the following method:

{< Field name >:< field value;}

Let's change the above query criteria to read as follows:

Collection.find ({userName: ' lone '});

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 '}). ToArray (function(Err, docs) {if(err) {Throwerr; } Else{console.log (docs);          Db.close ();      }        });  }    }); }});

After execution, the following appears:

2.2 You can specify the fields in the query selector that you want to query and limit the range of field values, as shown in the following method:

{< field name >:{$in:[< field value 1>,< field value 2> ...}}

Let's change the query criteria for the Find method to the following:

Collection.find ({username:{$in: [' Empty Intelligence ']}});

Here is all the code after the change, 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:{$inch: [' Empty Intelligence ']}}). ToArray (function(Err, docs) {if(err) {Throwerr; } Else{console.log (docs);          Db.close ();      }        });  }    }); }});

The results of the operation are as follows:

2.3 Specifying multiple fields for querying

In a complex query condition, you may want to specify a conditional query that specifies multiple field values at the same time. Below we are going to insert some data into our data, the code is 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 });varDocs =[{type:' Food ', price:11}, {type:' Food ', price:10}, {type:' Food ', price:9}, {type:' Food ', price:8}, {type:' Food ', price:9}];d B.open (function(err, db) {if(err) {Throwerr; } Else{Console.log (' Successfully established database connection '); Db.collection (' Users ',function(Err, collection) {Collection.insert (docs,function(Err, docs) {if(err) {Throwerr; } Else{console.log (docs);        Db.close ();  }      })    }); }});

As shown in the following:

Now let's query the data in which the Type field value equals ' food ' and the Price field value is less than 10, as shown in the following code:

Collection.find ({type: ' food ', price:{$lt: 10}})

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 ({type: ' food ', price:{$lt: Ten}}). ToArray (function(Err, docs) {if(err) {Throwerr; } Else{console.log (docs);          Db.close ();      }        });  }    }); }});

The execution effect is as follows:

2.4 Use the ' or ' relationship to specify the query criteria for multiple field values.

In a complex query condition, you may need to use ' or ' relationships to specify query criteria for multiple fields, such as now we query, Price is 11, or the Price field value is less than 9, use the following method:

collection.find ({  type:' food ',   $or: [    one},    9}}  ]);

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 ({type:' Food ', $or: [{price:11}, {price: {$lt:9} ]}). ToArray (function(Err, docs) {if(err) {Throwerr; } Else{console.log (docs);          Db.close ();      }        });  }    }); }});

As shown in the following:

Querying data in the MongoDB database (top)

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.