0

How to write mongodb query using java in this

 db.Tasks.find({'assignedMember': {'$elemMatch': {'userId': '54782bfce4b086cb31d51dd5', 'status': 'ASSIGNED'}}}).pretty()
1
  • Can you please be more clear on what you're trying to do? Commented Nov 24, 2016 at 17:28

1 Answer 1

1

Here is the Java code for the query in OP. You may need to change the collection name and database name accordingly in the below code.

MongoDB Java Driver Version = 3.2.2

import org.bson.Document;

import com.mongodb.MongoClient;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;

public class GetDataFromMongodbUsingElemMatch {
    public static void main(String[] args) {

        MongoClient client = new MongoClient();

        MongoDatabase database = client.getDatabase("localhost");

        MongoCollection<Document> userCollection = database.getCollection("users");

        FindIterable<Document> users = userCollection.find(Filters.elemMatch("assignedMember",
                Filters.and(Filters.eq("userId", "54782bfce4b086cb31d51dd5"), Filters.eq("status", "ASSIGNED"))));

        for (Document user : users) {
            System.out.println(user.toJson());
        }

        client.close();

    }

}

Test document used for testing this code:-

{
    "_id" : ObjectId("583805ac204e6a612ebaf7e0"),
    "assignedMember" : [ 
        {
            "userId" : "54782bfce4b086cb31d51dd5",
            "status" : "ASSIGNED"
        }
    ]
}

Output:-

{ "_id" : { "$oid" : "583805ac204e6a612ebaf7e0" }, "assignedMember" : [{ "userId" : "54782bfce4b086cb31d51dd5", "status" : "ASSIGNED" }] }
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.