Mongo使用空字段更新所有记录

编程入门 行业动态 更新时间:2024-10-28 03:23:04
本文介绍了Mongo使用空字段更新所有记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

如何更新将单个字段设置为"null"或根本没有值的所有Mongo文档?

How do I update all Mongo documents that have a single field set to 'null', or that doesn't have a value at all?

我有什么,但我不确定是否正确:

What I have, but I'm not sure if it's correct:

db.collection.update({name: {$eq: null}}, {$set: {name: 'test'}})

推荐答案

如果名称字段不存在,请尝试:

If the name field is not there try:

db.collection.update({"name": {"$exists": false}}, {"$set": {"name": "test"}})

$set 将添加具有指定值的新字段,前提是新字段不违反类型约束.

$set will add a new field with the specified value, provided that the new field does not violate a type constraint.

如果存在且为null,或者没有设置值:

If it is there and null, or does not have a value set:

db.collection.update({"name": null}, {"$set": {"name": "test"}})

您可以使用 $or 为

db.collection.update( { "$or": [ { "name": { "$exists": false } }, { "name": null } ] }, { "$set": { "name": "test" } } )

对于MongoDB 3.2及更高版本,请使用 updateMany() 会根据过滤器更新集合中的多个文档:

For MongoDB 3.2 and above, use updateMany() which updates multiple documents within the collection based on the filter:

db.collection.updateMany( { "$or": [ { "name": { "$exists": false } }, { "name": null } ] }, { "$set": { "name": "test" } } )

更多推荐

Mongo使用空字段更新所有记录

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

发布评论

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

>www.elefans.com

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