遇到问题---MongoDB--$not和$and搭配使用报错---operator $not is not allowed around criteria chain element: { "$an

来源:互联网 发布:淘宝的读书软件 编辑:程序博客网 时间:2024/05/20 14:24




报错

$not和$and搭配使用报错---operator $not is not allowed around criteria chain element: { "$and。


完整报错:

HTTP Status 500 - Request processing failed; nested exception is java.lang.IllegalArgumentException: operator $not is not allowed around criteria chain element: { "$and" 



正确用法

我们来看一个例子:

我们有数据:

{ "institution_type" : "A", "type" : "C" }
{ "institution_type" : "A", "type" : "D" }
{ "institution_type" : "B", "type" : "C" }
{ "institution_type" : "B", "type" : "D" }


想要获取 非 { "institution_type" : "A", "type" : "C" }的数据,应该使用:

query = { $not: { $and: [{institution_type:'A'}, {type:'C'}] } }

得到

{ "institution_type" : "A", "type" : "D" }
{ "institution_type" : "B", "type" : "C" }
{ "institution_type" : "B", "type" : "D" }



但是这种用法 mongodb不支持。


我们需要对思路进行一种转化:

NOT (A AND C)  

的用法等同于

 (NOT A)  OR (NOT C)


所以我们可以使用

db.collection.find({
  "$or": [
    {"institution_type": {"$ne": "A"}},
    {"type": {"$ne": "C"}}
  ]
})




java驱动中的用法


错误方式

    Criteria criteriaUpgrade=new Criteria();   criteriaUpgrade.not().andOperator(        Criteria.where("harvesterStatus").elemMatch(Criteria.where("status").is(40).and("datetime").gt(deadline)),        Criteria.where("harvesterStatus").elemMatch(Criteria.where("status").in(haveReport))        );



正确方式

    Criteria criteriaUpgrade=new Criteria();        criteriaUpgrade.orOperator(        Criteria.where("harvesterStatus").not().elemMatch(Criteria.where("status").is(40).and("datetime").gt(deadline)),        Criteria.where("harvesterStatus").not().elemMatch(Criteria.where("status").in(haveReport))        );





误导的方案


查资料过程中看到很多帖子上说 

NOT (A AND C)  

的用法也等同于

 NOR (A AND C)  


使用

db.collection.find({
  "$nor": [
    {"institution_type": "A"},
    {"type": "C"}
  ]
})


这种说法是错误,得到的数据要比 实际我们需要的会少一些。





阅读全文
0 0
原创粉丝点击