使用聚合将值添加到记录 [英] Add a value to to the record using aggregation

查看:72
本文介绍了使用聚合将值添加到记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的文档样本

  {
    _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

For the records which doesn't have present_working:true need to add 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"
  }
]

推荐答案

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

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.

这篇关于使用聚合将值添加到记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆