同一个MongoDB更新中的$ push和$ set [英] $push and $set in same MongoDB update

查看:490
本文介绍了同一个MongoDB更新中的$ push和$ set的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用MongoDB的Java驱动程序对同一操作中的记录进行两次更新($ set和$ push)。我正在使用类似于以下内容的代码:

I'm trying to use MongoDB's Java driver to make two updates ($set and $push) to a record in the same operation. I'm using code similar to the following:

    BasicDBObject pushUpdate = new BasicDBObject().append("$push", new BasicDBObject().append("values", dboVital));
    BasicDBObject setUpdate = new BasicDBObject().append("$set", new BasicDBObject().append("endTime", time));
    BasicDBList combinedUpdate = new BasicDBList();
    combinedUpdate.add( pushUpdate);        
    combinedUpdate.add( setUpdate);


    collection.update( new BasicDBObject().append("_id", pageId), combinedUpdate, true, false);

当我通过BasicDBList将$ set和$ push组合到同一个更新中时,我得到一个IllegalArgumentException :存储在数据库中的字段不能以'$'开头(坏键:'$ push')。

When I combine the $set and $push into the same update via a BasicDBList, I get an IllegalArgumentException: "fields stored in the db can't start with '$' (Bad Key: '$push')".

如果我进行两次单独的更新,则都是pushUpdate和setUpdate产生有效的结果。

If I make two separate updates, both pushUpdate and setUpdate produce valid results.

谢谢!

推荐答案

我不喜欢不懂Java驱动程序,但是你必须在那里创建一个列表吗?如果您尝试此代码会发生什么?

I don't know Java driver, but do you have to create a list there? What happens if you try this code?

BasicDBObject update = new BasicDBObject().append("$push", new BasicDBObject().append("values", dboVital));
update = update.append("$set", new BasicDBObject().append("endTime", time));

collection.update( new BasicDBObject().append("_id", pageId), update, true, false);

这应相当于

db.collection.update({_id: pageId}, {$push: {values: dboVital}, $set: {endTime: time}});

你的代码产生(我怀疑)这个:

Whereas your code produces (I suspect) this:

db.collection.update({_id: pageId}, [{$push: {values: dboVital}}, {$set: {endTime: time}}]);

这篇关于同一个MongoDB更新中的$ push和$ set的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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