MongoDB select where in array of _id?

前端 未结 5 1079
眼角桃花
眼角桃花 2020-11-29 23:59

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

相关标签:
5条回答
  • 2020-11-30 00:38

    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.

    0 讨论(0)
  • 2020-11-30 00:46

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

    var list = ["5883d387971bb840b7399130","5883d389971bb840b7399131","5883d38a971bb840b7399132"]
    
        .find({ _id: {$in : list}})
    
    0 讨论(0)
  • 2020-11-30 00:48

    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),
                  },
                },
            
    
    0 讨论(0)
  • 2020-11-30 00:53

    This is not related to mongo query. I was familiar with SQL and used Studio3T IDE to query a mongo database using SQL. If you are one like me, I want to point out that the id value needs to be typecasted. So the query will look like:

    SELECT _id from <collectionName>
    WHERE _id = ObjectId("5883d387971bb840b7399130");
    
    0 讨论(0)
  • 2020-11-30 00:57

    Easy :)

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

    taken from: http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24in

    0 讨论(0)
提交回复
热议问题