简体   繁体   English

嵌入文档数组中的MongoDB聚合ObjectId

[英]MongoDB Aggregate ObjectId inside Array of embedded Documents

I have seen a ton of question about the $lookup aggregator for arrays of ObjectIds but I can't seem to find anything about when the ObjectId is inside an array of embedded documents.我已经看到了很多关于 ObjectIds 数组的$lookup聚合器的问题,但我似乎无法找到有关 ObjectId 何时位于嵌入文档数组中的任何信息。

I have the follow document inside a mongodb database:我在 mongodb 数据库中有以下文档:

_id: ObjectId('...')
Alarms: [
  {
    Gateway: ObjectId('...')
    Port: 1
  },
  {
    Gateway: ObjectId('...')
    Port: 2
  }
]

I would like to have the following:我想要以下内容:

_id: ObjectId('...')
Alarms [
  {
    Gateway: ...(Gateway Object),
    Port: 1
  },
  {
    Gateway: ...(Gateway Object),
    Port: 2
  }
]

I have tried the following with no success:我尝试了以下方法但没有成功:

$lookup: {
  from: 'Gateway',
  localField: 'Alarms.Gateway',
  foreignField: '_id',
  as: 'Alarms.Gateway'
}

But this gives me the following result:但这给了我以下结果:

_id: ObjectId('...')
Alarms [
  {
    Gateway: {
      ...(Gateway Object)
    }
    Port: 1
  }
]

Please try the below queries :请尝试以下查询:

If you don't want the object which doesn't have match in Gateway collection exist in Alarms array in final result :如果您不希望最终结果中的Alarms数组中存在Gateway集合中不匹配的对象:

db.Alarms.aggregate([{ $unwind: '$Alarms' }, {
    $lookup: {
        from: 'Gateway',
        localField: 'Alarms.Gateway',
        foreignField: '_id',
        as: 'Alarms.Gateway'
    }
}, { $match: { 'Alarms.Gateway': { $ne: [] } } },
{ $addFields: { 'Alarms.Gateway': { $arrayElemAt: ['$Alarms.Gateway', 0] } } },
{ $group: { _id: '$_id', Alarms: { $push: '$Alarms' } } }
])

Test : MongoDB-Playground测试: MongoDB-Playground

Otherwise, if you want all objects in Alarms array to be returned irrespective of whether there is a match in Gateway or not :否则,如果您希望返回Alarms数组中的所有对象,而不管Gateway中是否存在匹配项:

db.Alarms.aggregate([{ $unwind: '$Alarms' }, {
    $lookup: {
        from: 'Gateway',
        localField: 'Alarms.Gateway',
        foreignField: '_id',
        as: 'Alarms.GatewayObj'
    }
}, { $addFields: { 'Alarms.Gateway': { $cond: [{ $ne: ['$Alarms.GatewayObj', []] }, { $arrayElemAt: ['$Alarms.GatewayObj', 0] }, '$Alarms.Gateway'] } } },
{ $project: { 'Alarms.GatewayObj': 0 } },
{ $group: { _id: '$_id', Alarms: { $push: '$Alarms' } } }
])

Test : MongoDB-Playground测试: MongoDB-Playground

Difference between two queries would be one will return below object in Alarms array (Vs) one don't.两个查询之间的区别是一个将返回Alarms数组(Vs)中的对象下方,一个不会。

{
    "Gateway": ObjectId("5e2b5425d02e05b6940de2fb"),
    "Port": 2
 }

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

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