Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/mongodb/13.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
MongoDB:如何在聚合上应用多个$project_Mongodb_Mongodb Query_Aggregation Framework - Fatal编程技术网

MongoDB:如何在聚合上应用多个$project

MongoDB:如何在聚合上应用多个$project,mongodb,mongodb-query,aggregation-framework,Mongodb,Mongodb Query,Aggregation Framework,下面给出的是my_集合 { "_id":ObjectId("5b3f4e1013aad111501b34c4") "Text":["kjsdf sdfjgnks vk ekl sdsdd."], "Title":["lkdjf wufk"], "List":["3412","1244","7654","8476"], "__v":0 } 我想在我的\u集合上进行聚合,以便: 生成一个字段“totalist”,其中包含字段“List”中数组中的项目计数 防止字段“_v”显示在

下面给出的是
my_集合

{
  "_id":ObjectId("5b3f4e1013aad111501b34c4")
  "Text":["kjsdf sdfjgnks vk ekl sdsdd."],
  "Title":["lkdjf wufk"],
  "List":["3412","1244","7654","8476"],
  "__v":0
}
我想在
我的\u集合上进行聚合,以便:

  • 生成一个字段“totalist”,其中包含字段“List”中数组中的项目计数
  • 防止字段“_v”显示在结果中
  • 将输出字段“List”的值更改为数组的联接
  • 删除“列表”中字符串末尾的尾随逗号
  • 缩短第4点生成的字符串,使其仅包含“列表”字段中的前50个字符
  • 所以我写了这段代码:

      db.my_collection.aggregate( 
          [ 
             {
               $addFields: {
                 totalList: { $size: "$List" }  // I can achieve the 1st point with this
               }
             },
             { $project : { 
                              __v:0,  // I can achieve the 2nd point with this
                              List:
                              {
                                $reduce:  // I can achieve the 3rd point with this
                                   {
                                     input: "$List",
                                     initialValue: "",
                                     in: { $concat : ["$$value", "$$this", ","] }
                                   }
                              }
                           }
              }
          ] 
      );
    
    但是,在运行上述命令时,出现以下错误:

      Failed to execute a script.
    
      Error:
      Assert: command failed: {
        "ok" : 0,
        "errmsg" : "Bad projection specification, cannot include fields or add computed fields during an exclusion projection: { __v: 0.0, List: { $reduce: { input: \"$List\", initialValue: \"\", in: { $concat: [ \"$$value\", \"$$this\", \",\" ] } } } }",
        "code" : 40182,
        "codeName" : "Location40182"
      } : aggregate failed
      _getErrorWithCode@src/mongo/shell/utils.js:25:13
      doassert@src/mongo/shell/assert.js:16:14
      assert.commandWorked@src/mongo/shell/assert.js:370:5
      DBCollection.prototype.aggregate@src/mongo/shell/collection.js:1319:5
      DBCollection.prototype.aggregate@:1:355
      @(shell):1:1
    
      Error: command failed: {
        "ok" : 0,
        "errmsg" : "Bad projection specification, cannot include fields or add computed fields during an exclusion projection: { __v: 0.0, List: { $reduce: { input: \"$List\", initialValue: \"\", in: { $concat: [ \"$$value\", \"$$this\", \",\" ] } } } }",
        "code" : 40182,
        "codeName" : "Location40182"
      } : aggregate failed :
      _getErrorWithCode@src/mongo/shell/utils.js:25:13
      doassert@src/mongo/shell/assert.js:16:14
      assert.commandWorked@src/mongo/shell/assert.js:370:5
      DBCollection.prototype.aggregate@src/mongo/shell/collection.js:1319:5
      DBCollection.prototype.aggregate@:1:355
      @(shell):1:1
    
    因此,我将其改写为:

      db.my_collection.aggregate( 
          [ 
             {
               $addFields: {
                 totalList: { $size: "$List" }  // Achieve the 1st point with this
               }
             },
             { $project : { 
                              "Text":1,
                              "Title":1,
                              __v:{     // Achieve the 2nd point with this
                                  $cond: {
                                     if: { $eq: [1,1] },
                                     then: "$$REMOVE",
                                     else: 0
                                  }
                              },
                              List:
                              {
                                $reduce:  // Achieve the 3rd point with this
                                   {
                                     input: "$List",
                                     initialValue: "",
                                     in: { $concat : ["$$value", "$$this", ","] }
                                   }
                              }
                           }
              }
          ] 
      );
    
    现在,我可以达到前3点。

    但是,我怎样才能达到第四点和第五点呢?

    您可以在下面尝试

    db.collection.aggregate([
      { "$addFields": {
        "totalList": { "$size": "$List" },
        "List": {
          "$substr": [
            { "$reduce": {
              "input": "$List",
              "initialValue": "",
              "in": { "$concat": ["$$value", ",", "$$this"] }
            }},
            1,
            50
          ]
        }
      }},
      { "$project": { "List": 1, "Test": 1, "Title": 1, "totalList": 1 }}
    ])
    
    输出

    [
      {
        "List": "3412,1244,7654,8476",
        "Title": [
          "lkdjf wufk"
        ],
        "_id": ObjectId("5b3f4e1013aad111501b34c4"),
        "totalList": 4
      }
    ]
    

    试试看

    请尝试以下聚合。我在下面的评论中提到了#4和#5的变化

    db.sample.aggregate( 
        [ 
         {
           $addFields: {
             totalList: { $size: "$List" } //This is for #1
           }
         },
         { $project : { 
                          "Text":1,
                          "Title":1,
                          "totalList":1,
                          __v:{     
                              $cond: {
                                 if: { $eq: [1,1] }, //This is for #2
                                 then: "$$REMOVE",
                                 else: 0
                              }
                          },
                          List:
                          {
                            $reduce: //This is for #3
                               {
                                 input: "$List",
                                 initialValue: "",
                                 in: {
                                       $concat: [
                                         "$$value",
                                         {
                                           $cond: { 
                                             if: { $eq: [ "$$value", "" ] }, //This is for #4
                                             then: "",
                                             else: ", "
                                           }
                                         },
                                         "$$this"
                                       ]
                                     }
                               }
                          }
                       }
          },
          {
            $project : { 
                          "Text" : 1,
                          "Title" : 1,
                          "__v" : 1,
                          "List" : { $substr: [ "$List", 0, 50 ] }, //This is for #5
                          "totalList":1
            }
    
          }
        ] 
    );
    

    使用
    $addFields
    添加字段
    \u v
    列表
    ,然后在列表末尾使用
    $project
    pipeline@AnthonyWinzlet,实际上,我不想在输出中显示
    \uu v
    ,而是像第1、3、4和5点中提到的那样,在
    列表中计算一些东西。请参见我的问题描述中的示例文档格式。用@AnthonyWinzlet试试这个,太棒了!但是我尝试了包装
    $rtrim
    ,就像你包装
    $substr
    一样,它在mongoplayground.net上有效,但在我本地的mongodb上无效。你可以在这里找到我的更新代码,这太棒了!但是我尝试了包装
    $rtrim
    ,就像你包装
    $substr
    一样,它在mongoplayground.net上有效,但在我本地的mongodb上无效。你可以在这里@TempO'rary找到我的更新代码你的mongodb版本是什么?因为
    $rtrim
    在最新版本4.0中引入了。。。但是你可以使用上面的聚合,它也可以从3.6版开始工作哦!我的是3.4。那么,我如何修剪前导和尾随的逗号呢?哦,那么你唯一的改变就是逗号在这里的位置
    “$concat”:[“$$value”,“,”,“$$this”]
    ,并将
    “$substr”
    的第二个参数设置为1。对吗?没有其他改变,对吧?正是@节奏