Search code examples
mongodbmongodb-queryaggregation-frameworkmongodb-java

Mongo DB regex aggregation query using java API


I want to query using regex and aggregation in mongo db, the following is working fine in mongo shell but how to write the same using Java API.

    db.posts_collection.aggregate({$unwind:"$posts"},
    {$match :{"posts.message":/.*keyword.*/} })

I tried using the following but unable to get the required result,

    BasicDBObject unwind = new BasicDBObject("$unwind","$posts");
    BasicDBObject matchKeyWord = new BasicDBObject("$match",new
    BasicDBObject("posts.message",java.util.regex.Pattern.compile("keyword")));
    AggregationOutput output = collection.aggregate(unwind,matchKeyWord);

Please tell me how to write the same query in java.


Solution

  • I would think that should work, but if you really wanted to be sure use the $regex operator form instead:

        BasicDBObject unwind = new BasicDBObject("$unwind","$posts");
        BasicDBObject matchKeyWord = new BasicDBObject(
            "$match",new BasicDBObject(
                "posts.message",new BasicDBObject("$regex",".*keyword.*")
            )
        );
        AggregationOutput output = collection.aggregate(unwind,matchKeyWord);
    

    That operator exists for the purpose of "safe" serialization with differing drivers.