How to build a $ ObjectIds query using QueryBuilder with MongoDB

I am trying to build a $ query with QueryBuilder (MongoDB Java API 2.9.1). I have no problem when a query is an array of strings, but when I try to use an ObjectIds array, it does not work (returns nothing).

I can successfully execute the request and get the result from the console:

A query in the console: db.collection.find ({deleted: false, app_id: {$ in: [ObjectId ("4f75c533ac99d845186e19b2"), ObjectId ("4f75c533ac99d845186e19b3")]}}))

Query created by QueryBuilder (MongoDB Java API 2.9.1):

Object [] ids;

Java code: DBObject query = QueryBuilder.start ("app_id"). In (ids) .and ("removed"). Is (false) .get ();

ToString in DBObject creates: {"app_id": {"$ in": [{"$ oid": "4f75c533ac99d845186e19b2"}]}, "removed": false}

Not sure if I am doing something wrong or the API does not support $ in a request like ObjectId. Any ideas?

+4
source share
1 answer

Your identifiers should be of type org.bson.types.ObjectId , so something like this should work:

 import org.bson.types.ObjectId; ObjectId[] ids = new ObjectId[]{ new ObjectId("1234568abcd"), new ObjectId("1234567abcd")}; DBObject query = QueryBuilder.start("app_id").in(ids) .and("removed").is(false).get(); 
-2
source

Source: https://habr.com/ru/post/1438636/


All Articles