开发者

MongoDB select where in array of _id?

开发者 https://www.devze.com 2023-04-12 03:54 出处:网络
is possible in mongo db to select collection\'s documents like in SQL : SELECT * FROM collection WHERE _id IN (1,2,3,4);

is possible in mongo db to select collection's documents like in SQL :

SELECT * FROM collection WHERE _id IN (1,2,3,4);

or if i have a _id array i must select one by one and then recompose the array/object 开发者_StackOverflow中文版of results?


Easy :)

db.collection.find( { _id : { $in : [1,2,3,4] } } );

taken from: https://www.mongodb.com/docs/manual/reference/operator/query/in/#mongodb-query-op.-in


Because mongodb uses bson and for bson is important attribute types. and because _id is ObjectId you must use like this:

db.collection.find( { _id : { $in : [ObjectId('1'),ObjectId('2')] } } );

and in mongodb compass use like this:

{ "_id" : { $in : [ObjectId('1'),ObjectId('2')] } }

Note: objectId in string has 24 length.


You can try this

var ids = ["5883d387971bb840b7399130","5883d389971bb840b7399131","5883d38a971bb840b7399132"];

var oids = [];
ids.forEach(function(item){
oids.push(new ObjectId(item));
});

.find({ _id: {$in : oids}})


MongoDB select where in array of _id?

In this code list is the array of ids in user collection

var list = ["5883d387971bb840b7399130","5883d389971bb840b7399131","5883d38a971bb840b7399132"]

    .find({ _id: {$in : list}})


if you want to find by user and also by another field like conditionally, you can easily do it like beneath with spread and ternary operator using aggregate and match

 const p_id = patient_id;
    let fetchingReports = await Reports.aggregate([
      ...(p_id
        ? [
            {
              $match: {
                createdBy: mongoose.Types.ObjectId(id),
                patient_id: p_id,
              },
            },
          ]
        : [
            {
              $match: {
                createdBy: mongoose.Types.ObjectId(id),
              },
            },
        


The query should be something like this:

db.collection.find( { 
        "_id": {
            "$in": [
                "475B9A5029D21",
                "385D808029D81",
                "C3463BD029DBB",
                "B839DB5029FFF"
            ]
        }
 } );
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号