在猫鼬中没有对象 ID 的数据合并

我正在使用猫鼬。

就像'Mysql Join'一样,
我想得到下面合并父子集合的数据。

父母

[
    {
        type: "A",results: [
            {
                "id": 111111
            },{
                "id": 222222
            }
        ]
    },{
        type: "B",results: [
            {
                "id": 333333
            },{
                "id": 444444
            }
        ]
    }
]

儿童

[
    {
        dataId: 111111,results: [
            { "status": { key: "value" } }
        ]
    },{
        dataId: 222222,{
        dataId: 333333,{
        dataId: 444444,]

因为不能插入ObjectId,
好像不能用population方法处理。
我想合并两个数据,比如在 MySQL 中加入。
如下图

Parent.find()

[
    {
        type: "A",results: [
            {
                "id": 111111,results: [
                    { "status": { key: "value" } }
                ]
            },{
                "id": 222222,results: [
                    { "status": { key: "value" } }
                ]
            }
        ]
    },results: [
            {
                "id": 333333,{
                "id": 444444,results: [
                    { "status": { key: "value" } }
                ]
            }
        ]
    }
]
zcg234 回答:在猫鼬中没有对象 ID 的数据合并

您可以使用此查询:

  • $unwind 获取数组中的每个结果以与子节点 dataid 合并。
  • $lookup 是 mongodb 中的“加入”。这里的查询是将字段 id 合并到 results 中,来自父级,dataId 来自子级。
  • $unwind 再次,因为 $lookup 创建了一个数组。
  • $group 根据 id 对值进行分组。
  • $project(此阶段是可选的)以不显示您不想要的字段。
yourParentModel.aggregate([
  {
    "$unwind": "$results"
  },{
    "$lookup": {
      "from": "Child","localField": "results.id","foreignField": "dataId","as": "child_results"
    }
  },{
    "$unwind": "$child_results"
  },{
    "$group": {
      "_id": "$_id","type": {
        "$first": "$type"
      },results: {
        "$push": "$child_results"
      }
    }
  },{
    "$project": {
      "_id": 0,"results._id": 0
    }
  }
])

示例here

,

您可以直接从 javascript 执行此操作

首先你从 mongoDB 获取父级 (使用猫鼬查找方法)

let parents = [
  {
    type: "A",results: [
      {
        id: 111111,},{
        id: 222222,],{
    type: "B",results: [
      {
        id: 333333,{
        id: 444444,];

然后你从数据库中获取孩子

let children = [
  {
    dataId: 111111,results: [{ status: { key: "value" } }],{
    dataId: 222222,{
    dataId: 333333,{
    dataId: 444444,];

将父母与孩子合并的处理将是这样的


for (let parent of parents) {
  for (let objectId of parent.results) {
    for (let child of children) {
      if (child.dataId === objectId.id) {
        objectId.results = child.results;
        break;
      }
    }
  }
}
本文链接:https://www.f2er.com/8718.html

大家都在问