简体   繁体   中英

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?

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

need to become:

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

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM