如何在猫鼬中填充其他字段?

问题描述

我的第一个收藏值是:

coll1:

{
   _id:"5f82f1618cfa6d290c6271a9",name:"mehdi"
}

第二个收集值是:

coll2:

{
    _id:"5f82f1618cfa6d290c6271aa",fid:"5f82f1618cfa6d290c6271a9",family:"parastar"
}

我如何基于coll1中的 _id 和coll2中的 fid 填充?

我想成为这样的结果

{
   {
    _id:"5f82f1618cfa6d290c6271aa",family:"parastar"
   },name:"mehdi"
}

您有这样做的主意吗?

解决方法

您必须以这种方式使用 $lookup

db.coll1.aggregate([
  {
    $lookup: {
      from: "coll2",localField: "_id",foreignField: "fid",as: "collection"
    }
  }
])

此查询使用您想要的数据创建一个名为 collection 的字段:

[
  {
    "_id": "5f82f1618cfa6d290c6271a9","collection": [
      {
        "_id": "5f82f1618cfa6d290c6271aa","family": "parastar","fid": "5f82f1618cfa6d290c6271a9"
      }
    ],"name": "mehdi"
  }
]

示例here

使用Mongoose也是一样,只写这样的查询:

var agg = await model.aggregate([
    {
      $lookup: {
        from: "coll2",as: "collection"
      }
    }
  ])
console.log(agg)

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...