简体   繁体   中英

mongodb array query for search bar

I am trying to return documents where at least one element from the selected field array matches the query array.

I have tried the following queries:

const match_equipment = await studios.find({equipment: {$eleMatch:{$in: ["mic","amp"]}}});
const match_equipment = await studios.find({equipment: {$all: ["mic","amp"]}});

The 1st query gives me "db query failed error" 2nd one gives me "no result found".

Sample document:

{
    "_id": {"$oid": "5ec5d38be97c8869bee29e78"},
    "equipment": ["guitar", " mic", " amp"],
    "studio_name": "Best recordings",
    "email": "changed@gmail.com",
    "address": "34 harming st. Brunswick",
    "postcode": "3056",
    "price": "50",
    "__v": {"$numberInt": "0"},
    "unavalibility": [
        {
            "times": [{"$numberInt": "13"}],
            "_id": {"$oid": "5ec610e47cf2fb4e84ba0c54"}, "date": {"$date": {"$numberLong": "1591920000000"}}
        }
    ]
}

You are very close, you just have a syntax error.

It's $elemMatch and not eleMatch

So changing it will work:

const match_equipment = await studios.find({equipment: {$elemMatch:{$in: ["mic","amp"]}}});

But the essence of $elemMatch is more specialised queries. Which in your case are not required. So you can just use the following version utilizing $in only:

const match_equipment = await studios.find({equipment: {$in: ["mic","amp"]}});

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