2

我有两个 MongoDB 集合,我想用图像对象替换所有 ID。

数据集集合:

{ 
  _id: 5d888b3a29cf9a5e93d80756,
  date: 2019-09-23T11:33:00.000Z,
  robot: { _id: 5d9c7caf0ad3ea493210527b, name: 'erx01' },
  images:[ 
    { 
      rgb: 5da57db7cacd6e00c2a0f677,
      ir: 5da57db7cacd6e00c2a0f678,
      lbl: 5da57db7cacd6e00c2a0f676 
    },
    { 
      rgb: 5da5808f65f3440032edee78,
      ir: 5da5808f65f3440032edee79,
      lbl: 5da5808f65f3440032edee77 
    } 
  ] 
}

图片集:

{ 
  _id: 5da57db7cacd6e00c2a0f677,
  filename: 'iI7gVXyf31b1wedzBXD.png',
  metadata: [Object],
  type: 'RGB' 
}

这就是我尝试并得到的结果:

{
  $unwind: "$images"
},
{
  $lookup: {
    from: "image",
    localField: "images.rgb",
    foreignField: "_id",
    as: "images.rgb"
  }
},
{
  $lookup: {
    from: "image",
    localField: "images.lbl",
    foreignField: "_id",
    as: "images.lbl"
  }
},
{
  $lookup: {
    from: "image",
    localField: "images.ir",
    foreignField: "_id",
    as: "images.ir"
  }
},

结果 :

images: { 
         rgb: [ [Object] ], 
         ir: [ [Object] ], 
         lbl: [ [Object] ] 
        }

我想要的是 :

images : [
           {
             rgb: [Object],
             ir:  [Object] , 
             lbl: [Object] 
           }
           { ... }
         ]

它工作了一半,因为我得到了正确的信息,但不是一个数组。我不想要一组 RGB/IR 和 LBL 图像,而是一组包含一个 RGB/IR/LBL 图像的对象。

我也尝试使用 unwind,但我没有任何相关信息。

4

1 回答 1

2

好吧,您做了一半正确的事情,您只需要添加组和项目即可将输出更改为所需的格式

{
    $unwind: "$images"
  },
  {
    $lookup: {
      from: "image",
      localField: "images.rgb",
      foreignField: "_id",
      as: "images.rgb"
    }
  },
  {
    $unwind: {
        "path": "$images.rgb",
        "preserveNullAndEmptyArrays": true
     }
  },
  {
    $lookup: {
      from: "image",
      localField: "images.lbl",
      foreignField: "_id",
      as: "images.lbl"
    }
  },
  {
   $unwind: {
        "path": "$images.lbl",
        "preserveNullAndEmptyArrays": true
     }
  },
  {
    $lookup: {
      from: "image",
      localField: "images.ir",
      foreignField: "_id",
      as: "images.ir"
    }
  },
  {
    $unwind: {
        "path": "$images.ir",
        "preserveNullAndEmptyArrays": true
     }
  },
  {
    $group: {
      _id: {
        id: '$_id',
      },
      date: { $last: '$date' },
      robot: { $last: '$robot' },
      images: { $push: '$images' }
    }
  },
  {
    $project: {
      _id: '$_id.id',
      date: 1,
      robot: 1,
      images: 1
    }
  }

注意 $unwind 在每次查找后都需要它,以便查找的输出不在数组中。

于 2019-10-15T09:57:12.083 回答