如何使用另一个对象的数组找到具有匹配ID的所有文档
How can I find all documents with a matching ID using an array of another object?
我有两个型号,Alarm
和Alert
。
AlertSchema
有一个引用Alarm
对象id的created_by
字段。
给定一个Alarm
对象数组,我如何找到所有相应的警报?
这不能工作(我并没有真正期望它)
// Get array of alarm objects
Alarm.find({unit: req.unit._id}).exec(function(err, alarms){
// Use array of alarm objects to find all alerts
Alert.find({created_by: alarms})
是我最好的选择,从每个对象提取_id到一个数组,并传递它作为一个参数,像这样:
Alarm.find({unit: req.unit._id}).exec(function(err, alarms){
var alarm_ids = alarms.map(function(o){return o._id});
// Use array of alarm objects to find all alerts
Alert.find({created_by: alarm_ids})
实际上可以使用 $lookup
操作符使用聚合框架和查询,这使得可以对另一个集合进行左外连接。
检查以下示例:
Alarm.aggregate([
{ "$match": { "unit": req.unit._id } },
{
"$lookup": {
"from": "alerts",
"localField": "_id",
"foreignField": "created_by",
"as": "alarm_alert"
}
},
{ "$unwind": "$alarm_alert "}
]).exec(function(err, result){
console.log(JSON.stringify(result, null, 4));
});
上面的查询是高效的,因为它是一个原子查询,并且使用了本地操作符。
在您的解决方案尝试中,您错过了 $in
操作符,作为拼图拼图的最终匹配,但有一件事让您感到遗憾的是,您正在重复调用服务器,即一次检索警报对象,另一次查询警报集合,因此它可能不如上述聚合操作高效:
Alarm.find({ "unit": req.unit._id })
.lean() // <-- return plain javascript objects
.exec(function(err, alarms){
var alarm_ids = alarms.map(function(o){return o._id});
// Use array of alarm objects to find all alerts
Alert.find({ "created_by": { "$in": alarm_ids } }).exec(callback);
});
相关文章:
- 将当前用户的 ID 推送到 meteorjs 中集合/文档的内部数组
- 如何获取文档id's在BaasBox[0.9.2]中使用java脚本
- 如何筛选要写入新文档的HTML,删除JavaScript中的某些类和/或ID
- node.js使用monk从数组中按id获取文档
- 如何使用文档的ID从mongoDB集合中删除文档
- 保存后访问子文档 ID - 猫鼬
- Mongoose子文档-找不到ID
- 获取文档的所有元素,id为'主导航'
- 更多相同的id´s在文档.getElementById(“”)中
- Meteor Update集合-未捕获错误:不允许.不受信任的代码只能通过ID更新文档.[403]
- JavaScript文档.getElementById(“id”)和元素id属性
- 检查数组是否在MongoDB文档中包含帖子ID
- 按文档 ID 加载 Mootools
- 我正在尝试遍历 id 数组,如果不存在 id,则插入一个 mongodb 文档.我怎样才能让他们坚持下去
- 来自不同集合的子文档 ID 数组的猫鼬架构
- 有没有办法使 ID 对于页面上的任何元素而不是文档的唯一性
- 流星通过ID错误删除文档
- Event.observe 仅适用于文档,不适用于特定 ID
- 我可以通过id从Mongo检索多个文档吗?
- Jquery选择ID文档选择ID