关于数组比较查询的问题

db.inventory.insertMany([
   { item: "journal", qty: 25, tags: ["blank", "red"], dim_cm: [ 14, 21 ] },
   { item: "notebook", qty: 50, tags: ["red", "blank"], dim_cm: [ 14, 21 ] },
   { item: "paper", qty: 100, tags: ["red", "blank", "plain"], dim_cm: [ 14, 21 ] },
   { item: "planner", qty: 75, tags: ["blank", "red"], dim_cm: [ 22.85, 30 ] },
   { item: "postcard", qty: 45, tags: ["blue"], dim_cm: [ 10, 15.25 ] }
]);

拿官网的例子来说
当使用{ tags: "red" }{ tags: {$eq: "red"} }是查询tags中,任一元素等于“red”。
当使用{ tags:{$ne: "red"} }却是查询tags中,所有元素不等于“red”。
感觉有些怪,不知道这个理解对不对。
然后又提供了一个操作符$elemMatch可以用来指定任一元素满足条件。也就是说{ tags: {$elemMatch:{$ne: "red"} } }任一元素不等于“red”。

那如果我想使用所有元素的比较查询,应该怎么办?比如所有的dim_cm都大于20。

阅读 1.5k
1 个回答

去找了下好像也没找到。但是可以换个思路,有一个小于就不满足就好了db.inventory.find( { dim_cm: {"$not":{ $lt: 25 }} } )

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进