简体   繁体   English

mongodb 更新集合中的字段同时自动生成另一个字段

[英]Mongodb update field in collection and at the same time generated automaticly another field

I have a collection which contain data's like this:我有一个包含如下数据的集合:

[{
_id: a,
createdAt: "2020-11-10",
createdBy: "test@test.com",
features: {
first: true,
second: true
}},{
_id: b,
createdAt: "2020-11-10",
createdBy: "test@test.com",
features: {
first: false,
second: true
}}]

I would like to insert a new feature: third: true我想插入一个新功能:第三:真

db.collection.update(  { _id:...} , { $set: { features.third : true  } } 

My questions is, is that possible to insert a new line for one of this feature and at the same time when the mongodb is see that there is a field like "third" and the value is true, than mongodb is generated a new field (featureConfig) automaticly which value is an empty string?我的问题是,是否可以为此功能之一插入新行,同时当 mongodb 看到有一个像“third”这样的字段并且值为 true 时,mongodb 会生成一个新字段( featureConfig) 自动哪个值是空字符串? so the expected value is :所以期望值是:

{
_id: b,
createdAt: "2020-11-10",
createdBy: "test@test.com",
features: {
first: false,
second: true,
third: true
},
featureConfig: "",
}

Any help would be appreciated.任何帮助,将不胜感激。

Try this query and check if it work as expected ( example )试试这个查询并检查它是否按预期工作(示例

This is the query:这是查询:

db.collection.aggregate([
  {
    "$match": {
      "id": 1
    }
  },
  {
    "$set": {
      "features.third": true
    }
  },
  {
    "$project": {
      "features": 1,
      "featureConfig": {
        "$cond": {
          "if": "$features.third",
          "then": "",
          "else": "$false"
        }
      }
    }
  }
])

The two initial stages are the same that you have, filter to match by id and set the value.两个初始阶段与您拥有的相同,过滤以按id匹配并设置值。 Then I've used $project to create a field featureConfig based in a condition.然后我使用$project根据条件创建了一个字段featureConfig If the features.third value is true, then create the field, otherwise not.如果features.third值为 true,则创建该字段,否则不创建。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM