0

Im using mongoose, I have the following data of user collection:

[{
    "_id": "1",
    "notes": [
        {
            "value": "A90",
            "text": "math"
        },
        {
            "value": "A80",
            "text": "english"
        },
        {
            "value": "A70",
            "text": "art"
        }
    ]
},
{
    "_id": "2",
    "notes": [
        {
            "value": "A90",
            "text": "math"
        },
        {
            "value": "A80",
            "text": "english"
        }
    ]
},
{
    "_id": "3",
    "notes": [
        {
            "value": "A80",
            "text": "art"
        }
    ]
}]

and I have as a parameters the following array: [ "A90", "A80" ]
so I want to make a query to use this array to return only the records that have all the array items in the notes (value) table.
So for the example above it will return:

[{
    "_id": "1",
    "notes": [
        {
            "value": "A90",
            "text": "math"
        },
        {
            "value": "A80",
            "text": "english"
        },
        {
            "value": "A70",
            "text": "art"
        }
    ]
},
{
    "_id": "2",
    "notes": [
        {
            "value": "A90",
            "text": "math"
        },
        {
            "value": "A80",
            "text": "english"
        }
    ]
}]

I tried the following find query:

{ "notes": { $elemMatch: { value: { $in: valuesArray } } }} 

but it returns a record even if just one element in valuesArray exist.

Alex Blex
  • 34,704
  • 7
  • 48
  • 75
Ayoub k
  • 7,788
  • 9
  • 34
  • 57
  • Did you try [find](https://mongoosejs.com/docs/api.html#model_Model.find) ? – Alex Blex Sep 11 '19 at 16:33
  • i tried the following : `{ "notes": { $elemMatch: { value: { $in: valuesArray } } }}` but it return a record even if just an element in `valuesArray` exist, i want to return a record if all the element in `valuesArray` exists in `note` – Ayoub k Sep 11 '19 at 16:36
  • 1
    Possible duplicate of [Find exactly match array or having all value of array in MongoDb](https://stackoverflow.com/questions/28735439/find-exactly-match-array-or-having-all-value-of-array-in-mongodb) – Alex Blex Sep 11 '19 at 16:48

1 Answers1

0

it turned out to be quite easy:

find({ "notes.value": { $all: arrayValues } })
Ayoub k
  • 7,788
  • 9
  • 34
  • 57