PHP User
PHP User

Reputation: 2422

MongoDB: How to find if $in is an object not an array

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

Answers (3)

Rahul Gupta
Rahul Gupta

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

Dheemanth Bhat
Dheemanth Bhat

Reputation: 4452

  1. Convert your recordId.id to integer using $toInt operator.
  2. Check if 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

D. SM
D. SM

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

Related Questions