2

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.

1
  • 1
    Then what results do you get? Commented Jun 21, 2014 at 10:10

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.