GrindCode
GrindCode

Reputation: 189

Mongodb find() with conditions doesn't work

I have multiple documents in a collection , and I want to get all documents which have a specific field value.

mongoClient.connect(serverUrl, { useUnifiedTopology: true }, function (err, client) {
                    if (err) throw err;
                    var db = client.db(useDB);

                    let arrayFind = [];
                    let var1 = 'id12345';
                    var cursor = db.collection('somecoll').find({},{"targetField":var1});
                    cursor.forEach(function (result) {
                        arrayFind.push(result);
                    }, function (error) { 
                        console.log(error);
                        console.log(arratFind);
                 });
});

But arrayFind is not filtered and I have ALL documents from my collection. How I put all documents in a array ? Do I need to filter it again with javascript?

Upvotes: 0

Views: 655

Answers (2)

Suchit Gupta
Suchit Gupta

Reputation: 1

as @R2D2 pointed out the query is wrong. Also,

db.collection.find()

returns an array result. Why do you want to push it in an array again?

Upvotes: 0

R2D2
R2D2

Reputation: 10737

 db.collection('somecoll').find({},{"targetField":var1})

need to become:

  db.collection('somecoll').find({"targetField":var1})

Upvotes: 1

Related Questions