MongoDB 在_id 数组中选择哪里?

可以在 mongodb 中选择 Collection 的文档,如 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?

122363 次浏览

简单:)

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

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

list is a array of ids

此代码列表中是用户集合中的 id 数组

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


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

因为 mongodb 使用 bson,而 bson 是重要的属性类型。因为 _idObjectId你必须这样使用:

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

mongodb compass中使用如下:

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

注意: 字符串中的 objectId 具有 24长度。

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

你可以试试这个

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


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


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