1 | initial version |
The process for searching keywords in MongoDB using node.js is as follows:
mongodb
module in node.js.const MongoClient = require('mongodb').MongoClient;
const url = 'mongodb://localhost:27017/mydatabase';
MongoClient.connect(url, function(err, db) {
if (err) throw err;
console.log('Database created!');
db.close();
});
find()
method. This method takes a query object as its argument that specifies the search criteria.db.collection('myCollection').find({ title: 'The Great Gatsby' }).toArray(function(err, result) {
if (err) throw err;
console.log(result);
db.close();
});
This query will find all documents in the myCollection
collection where the title
field is equal to 'The Great Gatsby'. The toArray()
method is used to convert the search results into an array.
title
field contains the word 'Gatsby', you can use the following:db.collection('myCollection').find({ title: /Gatsby/ }).toArray(function(err, result) {
if (err) throw err;
console.log(result);
db.close();
});
$or
operator in the query object. For example, to search for all documents where the title
field is either 'The Great Gatsby' or 'To Kill a Mockingbird', you can use the following:db.collection('myCollection').find({ $or: [ { title: 'The Great Gatsby' }, { title: 'To Kill a Mockingbird' } ] }).toArray(function(err, result) {
if (err) throw err;
console.log(result);
db.close();
});
This query will find all documents in the myCollection
collection where the title
field is either 'The Great Gatsby' or 'To Kill a Mockingbird'.