I recently upgraded from Mongoose 5.x to 8.x and one of my queries that previously worked is no longer returning any documents, and nothing in the migration guides seemed to indicate why that would be the case.
Here is a reduced/simplified example of one of the collection items from our fixture data:
{
_id: ObjectId('5ff8c2dd6b59a6000d7bfdb2'),
__t: 'Item',
name: 'Item Name',
tags: {
tag1: [
'option1',
'option2',
'option3',
],
tag2: [
'option1',
],
},
},
My query looks something like this:
{"$and":[{"$and":[{"tags.tag1":["option2"]},{"tags.tag2":["option1"]}]}
In Mongoose 5.x, the fixture document above would be returned from this query. However in 8.x, it is not. I tested a bunch of things and it turns out if I were to remove option1
and option3
such that the new tags object looked like this:
tags: {
tag1: [
'option2',
],
tag2: [
'option1',
],
},
then the item does get returned from the query. This seems to indicate that it will only be returned if the tag1 array matches the query exactly, rather than simply containing the item requested.
How would one ask Mongoose to return the document if the tag1 array includes option2
, even if there are other tags in the array?
4
Answers
Use
$setIsSubset
for comparison of 2 arrays.Mongo Playground
The issue is with the given values – [“option2”] and [“option1”].
In this case, it should be simply string values like “option2” and “option1”.
The modified query would be like this:
This is a detailed answer to the question. There is a short answer already posted separately. Request you may please start from there and proceed with this if not doing so.
There are two things to note – array match and value match. The following action log will demonstrate it.
$in operator is used to perform match a single value against array
As mentioned above please try executing query as mentioned in following link
https://mongoplayground.net/p/RQx2MJFivIK