Reputation: 2422
Let's say I have an array of ids
[1, 2, 3]
And these records
{"_id":"1",
"tableName":"users",
"recordId":{"id":"1"},
"__v":0}
{"_id":"2",
"tableName":"users",
"recordId":{"id":"2"},
"__v":0}
Now I want to find records which recordId.id exists in the ids array above how can I do that? As you see the problem here that recordId isn't array so I can access it directly using $in
Upvotes: 0
Views: 41
Reputation: 46
Simple solution to this is :
db.collection.find({ "recordId.id": { $in: arr_of_ids} });
Please note here that since in your given records, ids are given as strings, you have to pass an array of string ids.
Upvotes: 1
Reputation: 4452
recordId.id
to integer using $toInt operator.recordId.id
exists in ids
array using $in operator.Try this:
let ids = [1, 2, 3];
db.records.find({
$expr: {
$in: [{ $toInt: "$recordId.id" }, ids]
}
})
Upvotes: 0
Reputation: 14490
$in accepts an array of values. It doesn't require that the field values in the database are of an array type (though it also works for stored array values). Your use case is addressed by $in.
Upvotes: 1