Kevin Kevin - 1 year ago 132
Node.js Question

How to search an element in array using node.js in mongodb?

In mongodb there is a document like below,

"_id": ObjectId("57443657ee5b5ccc30c4e6f8"),
"name": "Kevin",
"email": "",
"password": "$2a$13$iZ0PhuY6VlBF6qC9rUredrG39Fw5pEKkIh.VCLiGsLPZMKYveyzey",
"mobile": "9980896745",
"__v": NumberInt(0),
"ocassionTypes": [
"occasiontype": "Anniversary",
"date": "2016-05-30T18:30:00.000Z"
"occasiontype": "Donation",
"date": "2016-07-24T18:30:00.000Z"
"occasiontype": "House Warming",
"date": "2016-09-21T18:30:00.000Z"

So I have written a query in Nodejs to search
element in
array like below,'/find-registry', function(req, res){
var uEmail =;
var uocType = req.body.userOccasion;
var findUserId = function(db, callback) {

var cursor =db.collection('users').find({email:uEmail, ocassionTypes: {$elemMatch: {occasiontype:uocType}}}).toArray(function(err, docs1){
callback(new Error("Some problem"));
} else {

MongoClient.connect(config.database, function(err, db) {
assert.equal(null, err);
findUserId(db, function(err,docs1) {
if(err) return res.json({result:null})
return res.json({result1:docs1});

Using this query I am getting 0th index element, but if I give 1st and 2nd element it always shows only 0th index in the output.

In front end I have given input as shown in the picture below.


front end image

Is there any wrong in my query? please help me to fix this.

Answer Source

your query is right but it will give matched document with full array

just add projection in your query

db.collection('users').find({email:uEmail, ocassionTypes: {$elemMatch: {occasiontype:uocType}}},{email:1, ocassionTypes: {$elemMatch: {occasiontype:uocType}}})
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download