文档字段名称不能以"$"开头(错误键:"$ set") [英] Document field names can't start with '$' (Bad Key: '$set')

查看:167
本文介绍了文档字段名称不能以"$"开头(错误键:"$ set")的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

    BasicDBObject u = new BasicDBObject();
    DBObject q = new BasicDBObject();
    q.put("orgId", orgId);
    u.append("orgId", orgId);

    if(accounts.keySet().size() > 0) {
        BasicDBObject setObj = new BasicDBObject();
        for (String key : accounts.keySet()) {
            String fieldToUpdate = "accounts." + key;
            setObj.append(fieldToUpdate, accounts.get(key));
        }
        u.append("$set", setObj);
    } 

    DBCollection collection = db.getCollection(collectionName);
    WriteResult result = collection.update(q, u, true, false);

我收到以下错误,这是怎么回事:

I get following error, what is wrong:

java.lang.RuntimeException: java.lang.IllegalArgumentException: Document field names can't start with '$' (Bad Key: '$set')

u.toString输出为:

u.toString output is :

{ "orgId" : 2 , "$set" : { "accounts.001" : "EXAMPLE"}}

推荐答案

更新文档中不应包含{ "orgId" : 2 }.

You should not have the { "orgId" : 2 } in the update document.

从代码中删除此行,它应该可以正常工作.

Remove this line from the code and it should work fine.

u.append("orgId", orgId);

您触发错误的原因是,有两种方法可以为文档指定更新,并且您创建了两者的交叉面包.选项是:

The reason you triggered the error was that there are two ways to specify the update for a document and you created a cross bread of both. The options are:

  1. 提供完整的更新文档.对于此模型,现有文档被提供的文档覆盖.
  2. 使用更新运算符来修改集合中的现有文档.

如果使用第二个版本,则更新文档中的所有顶级密钥"都将以$开头.如果使用第一个选项,则所有顶级键都不会以$开头.该代码查看了第一个字段,认为它是一个替换文档,然后在尝试验证该文档的其余部分是否有效时失败,因为文档中的键不能以$开头(因此请勿与更新或查询文档混淆) ).

If you use the second version then all of the "top level keys" in the update document will start with a $. If you use the first option then none of the top level keys will start with a $. The code looked at the first field, thought it was a replacement document and then failed when it tried to validate the rest of the document was valid since keys in documents cannot start with a $ (lest the be confused with update or query documents).

如果是upsert(例如,该文档尚不存在,并且您将更新标记为允许upsert),则使用查询的完全匹配运算符来播种该文档.对于上面的示例,我们获得{ "orgId" : 2 }的种子文档.然后,服务器将应用更新运算符并保​​存结果.

In the case of an upsert (e.g., the document does not already exist and you flag the update to allow the upsert) query's exact match operators are used to seed the document. For the above example we get a seed document of { "orgId" : 2 }. The server will then apply the update operators and save the result.

这篇关于文档字段名称不能以"$"开头(错误键:"$ set")的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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