HTML tutorial
CSS3 tutorial
Bootstrap tutorial
JavaScript tutorial
JQuery tutorial
AngularJS tutorial
React tutorial
NodeJS tutorial
PHP tutorial
Python tutorial
Python3 tutorial
Django tutorial
Linux tutorial
Docker tutorial
Ruby tutorial
Java tutorial
C tutorial
C ++ tutorial
Perl tutorial
JSP tutorial
Lua tutorial
Scala tutorial
Go tutorial
ASP.NET tutorial
C # tutorial
When finding documents in a collection, you can filter the result by using a query object
When finding documents in a collection, you can filter the result by using a query object.
The first argument of the find()
method
is a query object, and is used to limit the search.
Find documents with the address "Park Lane 38":
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/";
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db("mydb");
var query = { address: "Park Lane 38" };
dbo.collection("customers").find(query).toArray(function(err, result) {
if (err) throw err;
console.log(result);
db.close();
});
});
Save the code above in a file called "demo_mongodb_query.js" and run the file:
Run "demo_mongodb_query.js"
C:\Users\Your Name>node demo_mongodb_query.js
Which will give you this result:
[
{ _id: 58fdbf5c0ef8a50b4cdd9a8e
, name: 'Ben', address: 'Park Lane 38' }
]
You can write regular expressions to find exactly what you are searching for.
Regular expressions can only be used to query strings.
To find only the documents where the "address" field starts with the letter "S", use the regular
expression /^S/
:
Find documents where the address starts with the letter "S":
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/";
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db("mydb");
var query = { address: /^S/ };
dbo.collection("customers").find(query).toArray(function(err, result) {
if (err) throw err;
console.log(result);
db.close();
});
});
Save the code above in a file called "demo_mongodb_query_s.js" and run the file:
Run "demo_mongodb_query_s.js"
C:\Users\Your Name>node demo_mongodb_query_s.js
Which will give you this result:
[
{ _id:
58fdbf5c0ef8a50b4cdd9a8b , name: 'Richard',
address: 'Sky st 331' },
{ _id: 58fdbf5c0ef8a50b4cdd9a91 , name: 'Viola', address: 'Sideway
1633' }
]