我有一个 _ids 数组,我想相应地获取所有文档,最好的方法是什么?
就像是 ...
// doesn't work ... of course ...
model.find({
'_id' : [
'4ed3ede8844f0f351100000c',
'4ed3f117a844e0471100000d',
'4ed3f18132f50c491100000e'
]
}, function(err, docs){
console.log(docs);
});
该数组可能包含数百个 _id。
mongoose 中的 find
函数是对 mongoDB 的完整查询。这意味着您可以使用方便的 mongoDB $in
子句,其工作方式与 SQL 版本相同。
model.find({
'_id': { $in: [
mongoose.Types.ObjectId('4ed3ede8844f0f351100000c'),
mongoose.Types.ObjectId('4ed3f117a844e0471100000d'),
mongoose.Types.ObjectId('4ed3f18132f50c491100000e')
]}
}, function(err, docs){
console.log(docs);
});
即使对于包含数万个 id 的数组,这种方法也能很好地工作。 (见Efficiently determine the owner of a record)
我建议任何使用 mongoDB
的人通读优秀的 Official mongoDB Docs 的 Advanced Queries 部分
Ids 是对象 ID 的数组:
const ids = [
'4ed3ede8844f0f351100000c',
'4ed3f117a844e0471100000d',
'4ed3f18132f50c491100000e',
];
使用 Mongoose 和回调:
Model.find().where('_id').in(ids).exec((err, records) => {});
使用带有异步功能的 Mongoose:
const records = await Model.find().where('_id').in(ids).exec();
或者更简洁:
const records = await Model.find({ '_id': { $in: ids } });
不要忘记用您的实际模型更改模型。
ObjectId
数组(比如说,我有项目,我分配了具有在用户模型上引用的 project_id 的特定用户的项目数组),如果我删除一个项目,我如何确保从用户模型引用的数组中删除 id
?谢谢垫子。
结合丹尼尔和 snnsnn 的答案:
让 ids = ['id1','id2','id3'] 让数据 = await MyModel.find( {'_id': { $in: ids}} );
简单而干净的代码。它适用于并经过测试:
“mongodb”:“^3.6.0”,“猫鼬”:“^5.10.0”,
[]
内,但从您的回答中意识到它已经是一个数组:|
使用这种查询格式
let arr = _categories.map(ele => new mongoose.Types.ObjectId(ele.id));
Item.find({ vendorId: mongoose.Types.ObjectId(_vendorId) , status:'Active'})
.where('category')
.in(arr)
.exec();
从 mongoDB v4.2 和 mongoose 5.9.9 开始,这段代码对我来说很好用:
const Ids = ['id1','id2','id3']
const results = await Model.find({ _id: Ids})
并且 Id 可以是 ObjectId
或 String
类型
node.js 和 MongoChef 都强制我转换为 ObjectId。这就是我用来从数据库中获取用户列表并获取一些属性的方法。注意第 8 行的类型转换。
// this will complement the list with userName and userPhotoUrl based on userId field in each item
augmentUserInfo = function(list, callback){
var userIds = [];
var users = []; // shortcut to find them faster afterwards
for (l in list) { // first build the search array
var o = list[l];
if (o.userId) {
userIds.push( new mongoose.Types.ObjectId( o.userId ) ); // for the Mongo query
users[o.userId] = o; // to find the user quickly afterwards
}
}
db.collection("users").find( {_id: {$in: userIds}} ).each(function(err, user) {
if (err) callback( err, list);
else {
if (user && user._id) {
users[user._id].userName = user.fName;
users[user._id].userPhotoUrl = user.userPhotoUrl;
} else { // end of list
callback( null, list );
}
}
});
}
如果您使用的是 async-await 语法,您可以使用
const allPerformanceIds = ["id1", "id2", "id3"];
const findPerformances = await Performance.find({ _id: { $in: allPerformanceIds } });
我在下面尝试过,它对我有用。
var array_ids=['1','2','6','9'] // your array of ids
model.find({ '_id': { $in: array_ids }}).toArray(function(err, data) {
if (err) {
logger.winston.error(err);
} else {
console.log("data", data);
}
});
我正在使用此查询来查找 mongo GridFs 中的文件。我想通过它的 ID 来获得。
对我来说,此解决方案有效:Ids type of ObjectId
。
gfs.files
.find({ _id: mongoose.Types.ObjectId('618d1c8176b8df2f99f23ccb') })
.toArray((err, files) => {
if (!files || files.length === 0) {
return res.json('no file exist');
}
return res.json(files);
next();
});
这不起作用:Id type of string
gfs.files
.find({ _id: '618d1c8176b8df2f99f23ccb' })
.toArray((err, files) => {
if (!files || files.length === 0) {
return res.json('no file exist');
}
return res.json(files);
next();
});
{ _id : 5 }
与{ '_id' : 5 }
相同。