Hello again!
I think I must be missing something really simple but no matter how much I search the forums or ‘the internet’ I cannot find a way to $match documents that have a value of interest in an array. Take this simple data set for example (pastes straight into the ‘playground’):
[
{
"skills": [
"45",
"50"
],
"vectorname": "hereisthename",
"vectornumber": "50"
},
{
"skills": [
"1"
],
"vectorname": "killarney",
"vectornumber": "6"
},
{
"skills": null,
"vectorname": "weds-dup1",
"vectornumber": "35"
},
{
"skills": null,
"vectorname": "Dupo_Sun1",
"vectornumber": "29"
}
]
All I want to do is return the documents or objects which contain a specific value in the ‘skills’ array. Let’s just use “50” as the example:
db.collection.aggregate([
{
"$match": {
skills: {
$eq: "50"
}
}
}
])
BOOM! This works fine, matches the document with a skill in the array of value “50” so why does this fail?!?!?
db.collection.aggregate([
{
"$match": {
skills: {
$eq: "$vectornumber"
}
}
}
])
The dataset is manufactured as it is actually the result part way through a $lookup/pipeline where the number of interest is passed is as a $let statement. However, to make it simple I changed one of the documents to contain another field value that forces a match. Nothing works, there appears no way to specify a field instead of hard coding the “50”, and I have tried other more elaborate examples having surfed, such as this:
db.collection.aggregate([
{
"$match": {
"skills": {
$elemMatch: {
"$in": [
"$vectornumber",
"$skills"
]
}
}
}
}
])
Same result, no matches, the “$vectornumber” does not appear to resolve to “50” which we can see and prove does work. What am I missing because I cannot beleive I have to ‘unwind’ and rebuild the whole thing to match a simple array element… surely not?!
Please help put an old man out of his misery, what is wrong with the query when using the field name and how do I resolve this so I can search arrays against a value/field passed in using $let or similar?
Thanks a lot,
Martin.