【问题标题】:Add a value to to the record using aggregation使用聚合向记录添加值
【发布时间】:2020-07-03 17:07:10
【问题描述】:

我的文档样本

  {
    _id: "bmasndvhjbcw",
    name: "lucas",
    occupation: "scientist",
    present_working:true,
    age: 55,
    location: "texas",

  },
  {
    _id: "bmasndvhjbcx",
    name: "mark",
    occupation: "scientist",
    age: 45,
    present_working:true,
    location: "texas",
  },
  {
    _id: "bmasndvhjbca",
    name: "stuart",
    occupation: "lab assistant",
    age: 25,
    location: "texas",
  },
  {
    _id: "bmasndvhjbcq",
    name: "cooper",
    occupation: "physicist",
    age: 69,
    location: "texas"
  }
]

对于没有present_working:true的记录需要添加present_working:false

这样

  {
    _id: "bmasndvhjbcw",
    name: "lucas",
    occupation: "scientist",
    present_working:true,
    age: 55,
    location: "texas",

  },
  {
    _id: "bmasndvhjbcx",
    name: "mark",
    occupation: "scientist",
    age: 45,
    present_working:true,
    location: "texas",
  },
  {
    _id: "bmasndvhjbca",
    name: "stuart",
    occupation: "lab assistant",
    age: 25,
    present_working:false
    location: "texas",
  },
  {
    _id: "bmasndvhjbcq",
    name: "cooper",
    occupation: "physicist",
    age: 69,
    present_working:false,
    location: "texas"
  }
]

【问题讨论】:

  • 只是结果文档还是需要更新数据库中的文档?

标签: arrays mongodb-query aggregation-framework aggregate aggregation


【解决方案1】:

您可以根据需要使用其中一种:

db.collection.aggregate( [
  { $match: { present_working: { $exists: false } } },
  { $addFields: { present_working: false } }
] )

db.collection.aggregate( [
  { $addFields: { present_working: { $ifNull: [ "$present_working", false ] } } }
] )

第一个聚合仅返回具有新添加字段的文档。第二个有文档,有和没有添加的字段。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-07-20
    • 2020-05-08
    • 1970-01-01
    • 1970-01-01
    • 2013-11-17
    • 1970-01-01
    • 2017-09-05
    • 1970-01-01
    相关资源
    最近更新 更多