无论如何我可以在spring mongodb上的Update.addToSet()上做$each吗?
目前,当我将数组对象作为addToSet参数传递时, 它只使用$ addToSet而不使用$ each,导致将传递的数组放入现有数组中。
答案 0 :(得分:2)
我有一个自定义Update类的工作版本, 与https://jira.springsource.org/browse/DATAMONGO-471
中提出的解决方案混合使用public class MyUpdate extends Update {
public MyUpdate myAddToSet(String key, Object value, MongoOperations ops) {
BasicDBObject dbObject = new BasicDBObject();
ops.getConverter().write(value, dbObject);
this.addToSet(
key,
dbObject
);
// dont do this, will cause serialization exception
// System.out.println(this.getUpdateObject().toString());
return this;
}
public MyUpdate myAddToSetAll(String key, Collection<Object> values, MongoOperations ops) {
BasicDBList eachList = new BasicDBList();
for (Object value : values) {
BasicDBObject dbObject = new BasicDBObject();
ops.getConverter().write(value, dbObject);
eachList.add(dbObject);
}
this.addToSet(
key,
BasicDBObjectBuilder.start("$each", eachList).get()
);
// dont do this, will cause serialization exception
// System.out.println(this.getUpdateObject().toString());
return this;
}
public MyUpdate myPushAll(String key, Object[] values) {
super.addMultiFieldOperation("$pushAll", key, values);
return this;
}
public MyUpdate myPush(String key, Object[] values) {
super.addMultiFieldOperation("$push", key, values);
return this;
}
public MyUpdate myPush(String key, Object value) {
super.addMultiFieldOperation("$push", key, value);
return this;
}
}