To retrieve data from the MongoDB database we will use find, findOne with nodeJS promise.
In the first example, we use findOne which will return the first
const MongoClient = require('mongodb').MongoClient;
// Connection url
const url = 'mongodb://192.168.1.203:27017';
options = {
useNewUrlParser: true
};
MongoClient.connect(url, options).then(function (ok) {
db1 = ok;
dbName = 'testdb';
return db1.db(dbName).collection('test').findOne({"this":1});
})
.then(function (dbs) {
console.log(dbs);
db1.close();
});
This will return the data in nodeJS
$ node test.js
{ _id: 5bab60e785f572e55fe09165, this: 1, another: 'dfjfjdfdf' }
You can also use find().toArray to return all the documents with a field equals to the same value (here this: 1).
const MongoClient = require('mongodb').MongoClient;
// Connection url
const url = 'mongodb://192.168.1.203:27017';
options = {
useNewUrlParser: true
};
MongoClient.connect(url, options).then(function (ok) {
db1 = ok;
dbName = 'testdb';
return db1.db(dbName).collection('test').find({"this":1}).toArray();
})
.then(function (dbs) {
console.log(dbs);
db1.close();
});
This will return the following result in an array because I inserted three identical documents using insertOne:
$ node test.js
[ { _id: 5bab60e785f572e55fe09165, this: 1, another: 'dfjfjdfdf' },
{ _id: 5bab61018df000e560655d2d, this: 1, another: 'dfjfjdfdf' },
{ _id: 5bab6110b8724ae561d7191d, this: 1, another: 'dfjfjdfdf' } ]