Search code examples
javamongodbquery-buildermongo-java

Mongodb java Query Builder


I am new to java. How can I build this mongo query in java. Any help/hint will be appreciated.

db.places.find({loc : { $near :[ -122.934326171875,37.795268017578] , $maxDistance : 50 } ,$or:[{"uid":"at"},{"myList.$id" :ObjectId("4fdeaeeede2d298262bb80") } ] ,"searchTag" : { $regex : "Union", $options: "i"} } );

Solution

  • By using the QueryBuilder you can create the query you wanted. I have created it as follows.

    QueryBuilder query = new QueryBuilder();
    query.put("loc").near(-122.934326171875, 37.795268017578, 50);
    query.or(
            QueryBuilder.start("uid").is("at").get(),
            QueryBuilder.start("myList.$id").is(new ObjectId("5024f2f577a59dd9736ddc38")).get()
                );
    query.put("searchTag").regex(Pattern.compile("Union",Pattern.CASE_INSENSITIVE));
    

    When I print the query into the console it looks like :

    { "loc" : { "$near" : [ -122.934326171875 , 37.795268017578 , 50.0]} , 
      "$or" : [ { "uid" : "at"} , { "myList.$id" : { "$oid" : "5024f2f577a59dd9736ddc38"}}] , 
      "searchTag" : { "$regex" : "Union" , "$options" : "i"}
    }
    

    I didn't try it but hope it will work.