'How to compare a string with a string array in mongodb query condition

//PhoneProduct is model
//My schema has brand field with string type
var brands = ['apple', 'samsung'];
var QueryResult = PhoneProduct.find().where('brand').equals(brands));

Is there any way I get all document that have brand equal to any element in brands array ?



Solution 1:[1]

var QueryResult = PhoneProduct.find({'brand': {$in: brands }})

Solution 2:[2]

You can not campare string with array, for this you need to check it belongs from array or not, Try This

//PhoneProduct is model
//My schema has brand field with string type
var brands = ['apple', 'samsung'];
var QueryResult = PhoneProduct.find({brand: {$in: brands}})

Solution 3:[3]

You can compare with for (i) meaning a loop:

var myobj0 = { symbols: { $in: ["#" + "AVAX"] } }
find('XDB, 'XCOLLECTION', myobj0).then(result => {
    console.log("These are here", result)
    for (i = 0; i < result.length; i++) {
        console.log("IDS:" + result[i].id)
        bot.sendMessage(result[i].id, message);
    }
})

You can also define the strength to match (as in Regex, but more efficient, since MongoDB built in)

const find = async (dbName, collectionName, json) => {
    try {
        const collection = client.db(dbName).collection(collectionName);
        const result = await collection.find(json).collation( { locale: 'en', strength: 2 }).toArray();
        return result;
    } catch (err) {
        console.error(err);
    }
}

Maybe you just want to compare some asset that is already built in too. Please check collations here on Mongo official manual

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2
Solution 3