Mongo DB包含以下数据:
要求是,如果在此文档中存在字段,则增加计数器,否则插入字段。 一般情况下,当我们不确定它是否为insert或Update.But时,我们会使用upsert 数组元素
db.arrayexample.find()
{ "_id" : "userID", "addresses" : [ { "arrayid" : NumberLong(16694), "count" : 12 } ] }
我的Java代码如下:
MongoClient mongoClient = new MongoClient("localhost", 27017);
MongoDatabase mongoDatabase = mongoClient.getDatabase("testdb3");
MongoCollection mongoCollection = mongoDatabase.getCollection("arrayexample");
BasicDBObject query = new BasicDBObject();
query.put("_id", "userID");
query.put("addresses.arrayid",Long.valueOf(16695) );
mongoCollection.findOneAndUpdate(query,new Document("$inc", new Document("addresses.$.count", 1)),new FindOneAndUpdateOptions().upsert(true));
运行程序时出现以下错误:
' exception:如果没有包含数组的相应查询字段,则无法应用位置运算符。'在服务器localhost:27017。完整的回复是
"value" : null, "errmsg" : "exception: Cannot apply the positional operator without a corresponding query field containing an array.", "code" : 16650,
$ Upset是否适用于数组元素以及普通ID
答案 0 :(得分:1)
不,使用$ positional运算符时upserts将无效,如MongoDB文档中所述。
http://docs.mongodb.org/manual/reference/operator/update/positional/#upsert
编辑:作为一些风格,当与MongoDB的Jira https://jira.mongodb.org/browse/SERVER-10711
中的$ setOnInsert运算符结合使用时,似乎有一个开放的功能请求来支持这种特定类型的更新。