Any idea why this query
{
"_id": ObjectId("4e2a4ca7f21a81331f0006c3"),
"categories": {
"$nin": [
"Arts"
]
}
}
returns the following record when we explicitly excluded “Arts” with $nin above?
{
"_id": ObjectId("4e2a4ca7f21a81331f0006c3"),
"categories": {
"0": "Arts",
"1": "Arts - Performance"
}
}
as a sanity check, I changed $nin to $in
{
"_id": ObjectId("4e2a4ca7f21a81331f0006c3"),
"categories": {
"$in": [
"Arts"
]
}
}
and it didn’t return anything as expected.. but I’m still puzzled by the $nin result above!
Your first query is requesting a document with a specific ID and where the value for
categoriesis not in a list of strings (in this case,["Arts"]). The value forcategoriesfor this document is an embedded document,{ "0": "Arts", "1": "Arts - Performance" }.The second query returns nothing because that embedded document is not in the provided list of values for the
categoriesfield.Edit: If you want to be able to search for categories using
$inand$nin, you should consider converting thecategoriessubdocument into an array: