【问题标题】:cannot use the part to traverse the element不能使用零件遍历元素
【发布时间】:2018-04-28 20:07:00
【问题描述】:

我有这个问题:

 Query query = new Query();
 query.addCriteria(where("cakes.color.owner._id").is(new ObjectId(person.getId())));

 Update update = new Update();
 update.set("cakes.color.owner", person);

 mongoOperations.updateMulti(query, update, StockEntity.class);

这是我使用的对象的结构:

    public class StockEntity {        
            private List<Cake> cakes= new ArrayList<>();
    }

    public class Cake implements Serializable {
            private Color color;
    }

    public class Color implements Serializable {
            private Seller owner;
    }

问题是我得到了错误:

Write failed with error code 16837 and error message 'cannot use the part (cakes of cakes.color.owner) to traverse the element({cakes:[{cake:{color:{owner:_id:ObjectId('5a0c1bd15efad44437b2e76d')}}}]} )

为什么会出现这个错误?有什么想法吗?

谢谢!

【问题讨论】:

  • 因为您正在尝试更新数组中的字段
  • 我尝试使用 elemMatch 但我遇到了同样的错误。

标签: spring mongodb updates criteria spring-data-mongodb


【解决方案1】:

位置运算符 $ https://docs.mongodb.com/manual/reference/operator/update/positional/ 存在限制 我假设你使用 mongo 版本

试试这个:update.set("cakes.$.color.owner", person);

【讨论】:

  • 我认为这解决了问题,但问题是 mongo 版本 $ 总是自动更新第一个元素。
  • 是的,这就是我提到它有限制的原因。所以没有开箱即用的解决方案。如果你知道 cakes 的数量,你可以迭代每个循环。
猜你喜欢
  • 1970-01-01
  • 2019-01-17
  • 2015-09-06
  • 2023-03-26
  • 1970-01-01
  • 1970-01-01
  • 2012-07-26
  • 1970-01-01
  • 2018-11-11
相关资源
最近更新 更多