mongodb 我只需要一个对象数组

polkgigr  于 2023-06-05  发布在  Go
关注(0)|答案(1)|浏览(226)

我是MongoDB的新手,试图在一个查询中从两个表中获取数据,所有数据都应该在一个数组中,这样我就可以对它们的价格求和
在这里,我得到两个商店的产品id的数组,从该id我需要从各自的商店获取数据,并添加他们的价格,然后我需要发送到客户端的总价格
我的查询

db.store.aggregate([
{
"$lookup": {
  "from": "store1",
  pipeline: [
    {
      $match: {
        $expr: {
          "$in": [
            "$id",
            {
              "$map": {
                // your payload from client here
                "input": [
                  "63da2f1f7662144569f78dd6",
                  "63da2f1f7662144569f78dd7",
                  
                ],
                "as": "id",
                "in": {
                  "$toObjectId": "$$id"
                }
              }
            }
          ]
        }
      }
    },
    
  ],
  as: "store1"
}
},
{
$match: {
  $expr: {
    "$in": [
      "$id",
      {
        "$map": {
          // your payload from client here
          "input": [
            "63da2f1f7662144569f78ddd",
            "63da2f1f7662144569f78ddb",
            "63da2f1f7662144569f78dda"
          ],
          "as": "id",
          "in": {
            "$toObjectId": "$$id"
          }
        }
      }
    ]
  }
 }
},
{
$project: {
  _id: 0,
  
}
}
])

期望产量

[
{
"id": ObjectId("63da2f1f7662144569f78ddd"),
"name": "bat",
"price": 56,
 },
{
"id": ObjectId("63da2f1f7662144569f78ddb"),
"name": "cap",
"price": 100,
 },
{
"id": ObjectId("63da2f1f7662144569f78dda"),
"name": "red",
"price": 50,
  },
{
    "id": ObjectId("63da2f1f7662144569f78dd6"),
    "name": "bat",
    "price": 56
  },
  {
    "id": ObjectId("63da2f1f7662144569f78dd7"),
    "name": "ball",
    "price": 58
  }
 ]

下面是Mongodb playground链接https://mongoplayground.net/p/sMOizT0s2sC。在这里我提到了演示数据格式。

ruarlubt

ruarlubt1#

你可以使用$unionWith操作符(mongo 4.4版以上)来联合集合。pipeline基本上与您使用的

db.store.aggregate([
  {
    $match: {
      $expr: {
        $in: [
          "$id",
          {
            $map: {
              input: [ "63da2f1f7662144569f78ddd", "63da2f1f7662144569f78ddb", "63da2f1f7662144569f78dda" ],
              as: "id",
              in: { $toObjectId: "$$id" }
            }
          }
        ]
      }
    }
  },
  {
    $unionWith: {
      coll: "store1",
      pipeline: [
        {
          $match: {
            $expr: {
              $in: [
                "$id",
                {
                  $map: {
                    input: [ "63da2f1f7662144569f78dd6", "63da2f1f7662144569f78dd7" ],
                    as: "id",
                    in: { $toObjectId: "$$id" }
                  }
                }
              ]
            }
          }
        }
      ]
    }
  },
  {
    $project: { _id: 0 }
  }
])

playground

相关问题