Notification texts go here Contact Us Buy Now!

How to use $in with the _id

To utilize the $in operator with the _id field in MongoDB, you must ensure that you provide an array of MongoId's, rather than an array of MongoId of arrays, as the latter is not supported.

Therefore, it's necessary to preprocess your array before executing the query or maintain these ids as MongoId's.

You can conveniently accomplish this preprocessing using PHP's array_map function or a foreach loop. Below are illustrative examples of both methods:


// Using array_map()
$mongoIds = array_map(function($id) {
  return new MongoDB\BSON\ObjectId($id);
}, $array);

// Using foreach loop
$mongoIds = [];
foreach ($array as $id) {
  $mongoIds[] = new MongoDB\BSON\ObjectId($id);
}

Once you have an array of MongoId's, you can proceed to construct your query using the $in operator:


$query = [
  '_id' => [
    '$in' => $mongoIds
  ]
];

Executing this query will retrieve all documents where the _id field matches any of the provided MongoId's.

Post a Comment

Cookie Consent
We serve cookies on this site to analyze traffic, remember your preferences, and optimize your experience.
Oops!
It seems there is something wrong with your internet connection. Please connect to the internet and start browsing again.
AdBlock Detected!
We have detected that you are using adblocking plugin in your browser.
The revenue we earn by the advertisements is used to manage this website, we request you to whitelist our website in your adblocking plugin.
Site is Blocked
Sorry! This site is not available in your country.