Java MongoDB查询,插入2'$或'条件

时间:2015-11-11 16:20:03

标签: java mongodb

我正在尝试使用Java生成MongoDB查询,如下所示:

{
   "$or": [
      {
         "user": {
            "$exists": true
         }
      },
      {
         "parent": {
            "$exists":true
         }
      }
   ],
   "working": 1,
   "$or": [
      {
         "car.id": 3846,
         "car.mediaType": 1
      },
      {
         "car.matched.id": 3846,
         "car.matched.model": 1
      }
   ]
}

但是我不能这样做,因为当添加第二个$or条件时,第一个被覆盖。

我需要搜索每个$or的一些结果,我无法将其添加到同一个$or中。代码是:

import com.mongodb.BasicDBList;
import com.mongodb.BasicDBObject;
import com.mongodb.BasicDBObjectBuilder;

public class Sample {
    public function mongoSearch()
    {
        BasicDBObjectBuilder queryBuidlerType = BasicDBObjectBuilder.start().add("working", 1);

        BasicDBObject user = new BasicDBObject("user", new BasicDBObject("$exists", true));

        BasicDBObject parent = new BasicDBObject("parent", new BasicDBObject("$exists", true));

        BasicDBObject car = new BasicDBObject();
        parentMatch.put("car.id", mId);
        parentMatch.put("car.model", mModel);

        BasicDBObject carMatched = new BasicDBObject();
        parentMatch.put("car.matched.id", mId);
        parentMatch.put("car.matched.model", mModel);

        BasicDBList or1 = new BasicDBList();
        or.add(user);
        or.add(parent);

        BasicDBList or2 = new BasicDBList();
        or.add(car);
        or.add(carMatched);

        queryBuidlerType.add("$or", or1).add("$or", or2);

        DBObject queryType = queryBuidlerType.get();
    }
}

1 个答案:

答案 0 :(得分:2)

您应该使用$and包裹$or

{
   "$and": [
    {"$or": [
          {
         "user": {
            "$exists": true
         }
          },
          {
         "parent": {
            "$exists":true
         }
          }
       ]},
       {"$or": [
          {
         "car.id": 3846,
         "car.mediaType": 1
          },
          {
         "car.matched.id": 3846,
         "car.matched.model": 1
          }
      ]}
    ],
   "working": 1
}

而且,我也不知道你要做什么,但如果你想匹配" car.id":3846" AND" car.mediaType":1在同一个子对象中,考虑使用`$ elemMatch

在Java中:

QueryBuilder queryBuidlerType = QueryBuilder.start("working").is(1);

DBObject or1 = QueryBuilder.start().or(QueryBuilder.start("user").exists(true).get(), QueryBuilder.start("parent").exists(true).get()).get();
DBObject or2 = QueryBuilder.start().or(QueryBuilder.start("car.id").is(mId).and("car.model").is("mModel").get(), QueryBuilder.start("car.matched.id").is(mId).and("car.matched.model").is("mModel").get()).get();

queryBuidlerType.and(or1, or2);

DBObject queryType = queryBuidlerType.get();