本文介绍了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使用空字段更新所有记录
发布评论