【问题标题】:mongodb: updateOne set array of string if elements non present, leave unaltered if presentmongodb:如果元素不存在,则updateOne设置字符串数组,如果存在则保持不变
【发布时间】:2022-01-21 03:37:58
【问题描述】:

我在 mongodb 中有以下文档:

{
    "_id":"43434",
    "mail": "test@gmail.com"
    "category": ["Alimentari","Eventi","Ristorante","Servizi"]
}

我想编写java代码,这样如果:

  1. 我在输入 ["Alimentari","Eventi","Ristorante"] 中有以下字符串数组,文档保持不变
  2. 使用以下数组字符串 ["Alimentari","Bar"],文档将是:
{
    "_id":"43434",
    "mail": "test@gmail.com"
    "category": ["Alimentari","Eventi","Ristorante","Servizi","Bar"]
}
  1. 如果我传递一个仅包含一个字符串 ["Alimentari"] 的数组,则文档保持不变
  2. 如果我通过以下 ["Grande Distribuzione"],文档将是
{
    "_id":"43434",
    "mail": "test@gmail.com"
    "category": ["Alimentari","Eventi","Ristorante","Servizi","Grande Distribuzione"]
}

我用这段代码试过

    String[] category= {"Alimentari","Eventi","Ristorante"};
    collection.updateOne(
        new BasicDBObject("_id", new ObjectId(_id)),
        new BasicDBObject("$set", new BasicDBObject("category", category));

但生成的文档是:

{
    "_id":"43434",
    "mail": "test@gmail.com"
    "category": ["Alimentari","Eventi","Ristorante"]
}

你能帮帮我吗? 谢谢

【问题讨论】:

    标签: java mongodb


    【解决方案1】:

    对于 MongoDB 查询答案,如果值不存在,您需要 $addToSet$each 将多个值添加到 category 字段中。

    db.collection.update({
      _id: "43434"
    },
    {
      "$addToSet": {
        "category": {
          "$each": [
            "Alimentari",
            "Bar"
          ]
        }
      }
    })
    

    Sample Mongo Playground

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-08-20
      • 1970-01-01
      • 2012-03-28
      • 1970-01-01
      • 2011-02-17
      • 2022-11-14
      • 2016-04-16
      • 1970-01-01
      相关资源
      最近更新 更多