Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/fortran/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Database MongoDB使用$project按键从数组元素中获取_Database_Mongodb - Fatal编程技术网

Database MongoDB使用$project按键从数组元素中获取

Database MongoDB使用$project按键从数组元素中获取,database,mongodb,Database,Mongodb,我收集了以下文件 { _id:"1", address: "My office", email:"xxx@yyy.com", trxs:[ { type: 'sale', amount: 800 }, { type: 'buy', amount: 300 } ] }, { _id:"2", ad

我收集了以下文件

{
  _id:"1",
  address: "My office",
  email:"xxx@yyy.com",
  trxs:[
     {
       type: 'sale',
       amount: 800
     },
     {
       type: 'buy',
       amount: 300
     }
  ]
},
{
  _id:"2",
  address: "My house",
  email:"zzz@www.com",
  trxs:[
     {
       type: 'buy',
       amount: 200
     },
     {
       type: 'sale',
       amount: 400
     }
  ]
},
我想使用
$project
获取以下文档:

{
  email:"xxx@yyy.com",
  sale: 800,
  buy: 300
},
{
  email: "zzz@www.com",
  buy: 200,
  sale: 400
}
我不能使用
$arrayElementAt
,因为数组是随机的,销售可以位于位置0或1。

您可以展开“trxs”字段,然后使用$group和$cond将销售对象的值添加到销售字段,并将购买对象添加到购买字段

以下聚合可以解决您的问题:

db.test.aggregate([
  { $unwind: "$trxs" },
  {
    $group: {
      _id: "$_id",
      email: { $last: "$email" },
      sale: {
        $sum: { $cond: [{ $eq: ["$trxs.type", "sale"] }, "$trxs.amount", 0] },
      },
      buy: {
        $sum: { $cond: [{ $eq: ["$trxs.type", "buy"] }, "$trxs.amount", 0] },
      },
    },
  },
  { $project: { _id: 0 } },
]);

$unwind方法可以工作,但性能方面的速度非常慢。实际上,通过代码实现行为的速度更快,但我认为这不是一种正确的方法,因为DB必须更好地完成所有工作。有什么办法可以改进吗?