Mongo使用空字段更新所有记录 [英] Mongo update all records with a field that's null

查看:102
本文介绍了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使用空字段更新所有记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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