简体   繁体   中英

How to add where condition to the MongoDB whereObj in JavaScript

I am working on JavaScript with MongoDB.

I have collection name test_collection. It has field/object as test_field_1, which contains test_sub_field_1 and test_sub_field_2.

Now, I am putting

var whereObj = {};

var cursor = collection.find(whereObj, {
            '_id': 0
    
        });   

I tried to use test_sub_field_1.= 34 but it failed. I am trying to put where condition for test_sub_field_1,= 34 and test_sub_field_1.= 12. In current situation, whereObj is Empty.

var cursor = collection.find(whereObj, {
            '_id': 0,
            'test_field_1.test_sub_field_1': { $ne: 34 }
        });  

Thanks

find() in MongoDB takes 3 inputs: Query , Projection and Options (in that order).

You are passing whereObj as a Query input (which is empty object). You should change your code like this:

const whereObj = {
  'test_field_1.test_sub_field_1': { $ne: 34 }
};

const cursor = collection.find(whereObj);  

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