简体   繁体   English

MongoDB 选择_id 数组中的位置?

[英]MongoDB select where in array of _id?

is possible in mongo db to select collection's documents like in SQL :可以在 mongo db 中像在 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 of results?或者如果我有一个_id array我必须一一选择,然后重新组合结果的array/object

Easy :)简单 :)

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

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

Because mongodb uses bson and for bson is important attribute types.因为 mongodb 使用bson并且 bson 是重要的属性类型。 and because _id is ObjectId you must use like this:并且因为_idObjectId你必须像这样使用:

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

and in mongodb compass use like this:mongodb compass使用如下:

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

Note: objectId in string has 24 length.注意:字符串中的 objectId 长度为24

list 是一个 id 数组

In this code list is the array of ids in user collection在此代码列表中是用户集合中的 id 数组

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

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

You can try this你可以试试这个

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

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

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

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如果您想按用户以及有条件地按另一个字段查找,您可以使用aggregatematch轻松地使用扩展和三元运算符进行如下操作

 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),
              },
            },
        

is possible in mongo db to select collection's documents like in SQL :可以在mongo db中像在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 of results?还是如果我有一个_id array我必须一个一个地选择,然后重新组成结果的array/object

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM