使用聚合将值添加到记录

编程入门 行业动态 更新时间:2024-10-15 12:30:25
本文介绍了使用聚合将值添加到记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我的文档样本

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

更多推荐

使用聚合将值添加到记录

本文发布于:2023-11-22 14:28:45,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1617808.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!