Add a value to to the record using aggregation

我与影子孤独终老i 提交于 2020-03-28 06:39:17

问题


sample of my document

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

For the records which doesn't have present_working:true need to add present_working:false

Like this

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

回答1:


You can use one of these as per your need:

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

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

The first aggregation returns only the documents with the newly added field. The second has documents, with and without the added field.



来源:https://stackoverflow.com/questions/60810122/add-a-value-to-to-the-record-using-aggregation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!