如果 MongoDb 中尚不存在,如何将新元素推入现有数组或创建一个?

时间:2021-06-22 15:35:22

标签: arrays mongodb

我有一个创建文档、更新和清理文档的脚本。

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 但它无法识别该命令(没有错误,没有插入,没有合并,什么都没有)。

1 个答案:

答案 0 :(得分:0)

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

使用$cond方法

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

Mongo Playground Sample Execution

使用$ifNull方法

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

Mongo Playground Sample Execution

相关问题