0

我有一个脚本创建一个文档,更新它并清理它。

db.getCollection('things').insert( { _id: 1001, 
  elemo: { a: "A", b: "B" }, 
  histo: [ ] } } )
db.getCollection('things').update( { _id: 1001 },
  [ { $set: { 
    histo: { $concatArrays: [ "$histo", ["$elemo"] ] } } } ] )
db.getCollection("things").find({ _id: 1001})
db.getCollection('things').remove({ _id: 1001 })

出于某些原因,我想保留该功能,但不能保证原来的空数组确实存在。我需要以这样一种方式执行我的更新,以便现有数组将获得一个额外的元素,而一个不存在的(尚未)将被创建(包括所述元素)。

db.getCollection('things').insert( { _id: 1001, 
  elemo: { a: "A", b: "B" } } )
db.getCollection('things').update( { _id: 1001 },
  [ { $set: { 
    histo: { $concatArrays: [ "$histo", ["$elemo"] ] } } } ] )
db.getCollection("things").find({ _id: 1001})
db.getCollection('things').remove({ _id: 1001 })

以上仅创建字段,但其值为null,因此对其进行额外修改会导致null. 我很确定它需要更多的东西,$concatArrays但我不知道是什么。首先,我以为我可以去$ifnull,但它没有识别该命令(没有错误,没有插入,没有合并,什么都没有)。

4

1 回答 1

0

您可以使用$condor $ifNull(如您所料)来检查密钥是否存在于$concatArrays运算符内部。

使用$cond方法

db.collection.update({
  _id: 1001
},
[
  {
    $set: {
      histo: {
        "$concatArrays": [
          {
            "$cond": {
              "if": {
                "$not": [
                  "$histo"
                ]
              },
              "then": [],
              "else": "$histo",
              
            }
          },
          [
            "$elemo"
          ],
          
        ],
        
      }
    }
  }
])

Mongo Playground 示例执行

使用$ifNull方法

db.collection.update({
  _id: 1001
},
[
  {
    $set: {
      histo: {
        "$concatArrays": [
          {
            "$ifNull": [
              "$histo",
              []
            ],
            
          },
          [
            "$elemo"
          ],
          
        ],
        
      }
    }
  }
])

Mongo Playground 示例执行

于 2021-06-22T16:18:11.630 回答