如何取消设置除已知字段集以外的所有字段? [英] How do I unset all fields except a known set of fields?
问题描述
假设我的mongo集合中只有一个文档,如下所示:
Suppose I have a single document in my mongo collection that looks like this:
{
"_id": 123,
"field_to_prune":
{
"keep_field_1": "some value",
"random_field_1": "some value",
"keep_field_2": "some value",
"random_field_2": "some value",
"random_field_3": "some value"
}
}
我要修剪该文档,使其看起来像这样:
I want to prune that document to look like this:
{
"_id": 123,
"field_to_prune":
{
"keep_field_1": "some value",
"keep_field_2": "some value"
}
}
但是,我的问题是我不知道随机"字段名称是什么.在mongo中,除几个已知字段外,我将如何取消设置所有字段?
However, my issue is that I don't know what the "random" field names are. In mongo, how would i $unset all fields except a couple of known fields?
我可以想到几种方法,但是我不知道语法.我可以选择所有字段名称,然后为每个字段取消设置该名称.有点像这样:
I can think of a couple of ways, but i don't know the syntax.. i could select all field NAMES and then for each one of those unset the field. kind of like this:
[Some query to find all field names under "field_to_prune" for id 123].forEach(function(i) {
var key = "field_to_prune." + i;
print("removing field: " + key);
var mod = {"$unset": {}};
mod["$unset"][key] = "";
db.myCollection.update({ _id: "123" }, mod);
});
我正在考虑的另一种方法是取消设置字段名称不在我定义的字符串数组中的位置.也不知道该怎么做.有什么想法吗?
Another way I was thinking of doing it was to unset where the field name is not in an array of strings that i defined. not sure how to do that either. Any ideas?
推荐答案
如果您不关心原子性,则可以使用save
来实现:
If you don't care about atomicity then you may do it with save
:
doc = db.myCollection.findOne({"_id": 123});
for (k in doc.field_to_prune) {
if (k === 'keep_field_1') continue;
if (k === 'keep_field_2') continue;
delete doc.field_to_prune[k];
}
db.myCollection.save(doc);
此解决方案的主要问题是它不是原子的.因此,在findOne
和save
之间对doc
的任何更新都将丢失.
The main problem of this solution is that it's not atomic. So, any update to doc
between findOne
and save
will be lost.
替代方法是实际上unset
所有不需要的字段,而不是保存doc
:
Alternative is to actually unset
all unwanted fields instead of saving the doc
:
doc = db.myCollection.findOne({"_id": 123});
unset = {};
for (k in doc.field_to_prune) {
if (k === 'keep_field_1') continue;
if (k === 'keep_field_2') continue;
unset['field_to_prune.'+k] = 1;
}
db.myCollection.update({_id: doc._id}, {$unset: unset});
此解决方案更好,因为mongo原子运行update
,因此不会丢失任何更新.而且,您不需要其他集合即可完成所需的工作.
This solution is much better because mongo runs update
atomically, so no update will be lost. And you don't need another collection to do what you want.
这篇关于如何取消设置除已知字段集以外的所有字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!