使用聚合将值添加到记录

Add a value to to the record using aggregation

我的文件样本

  {
    _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"
  }
]

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

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

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

第一个聚合returns仅包含新添加字段的文档。第二个有文档,有和没有添加字段。