Multiple documents contain a key called userId
, where this key is always an object:
{
"id": {
"$oid": "22fc6b11a0ff111d598b114f"
},
"userId": {
"KEY1" : ["..."],
"KEY2" : ["..."],
"KEY3" : ["..."],
"KEY4" : ["..."]
}
}
Each document will always contain 4 sub-keys, with each being a non-empty array of strings
How can I search through all documents to find strings inside each of these KEY's?
For example:
/* MONGO document
{
"id": {
"$oid": "65fc6b08a0ffe6dd598b114f"
},
"userId": {
"KEY1" : ["1", "2", "3"],
"KEY2" : ["A", "Z"]
...
}
},
{
"id": {
"$oid": "22fc6b11a0ff111d598b114f"
},
"userId": {
"KEY1" : ["4", "5", "6"],
"KEY2" : ["Z", "X"]
...
}
}
*/
const array = ["2", "X"];
const users = await db.collection("users").find({ "userId": { "$in": array } }).toArray();
console.log(users)
const array = ["2", "X"];
<- Specifying an array of strings to find all documents
that contain any of these strings in any of the sub-key arrays of the userId
object
In this case, it would match both documents, because 2
exists in the first document's userId.KEY1
and X
exists in the second document's userId.KEY2
const array = ["X"];
This would match just the second document
My current attempt is not finding any matches, how can I achieve this?