简体   繁体   中英

How to write using hash map in this mongodb query using java

如何在此使用Java编写mongodb查询

 db.Tasks.find({'assignedMember': {'$elemMatch': {'userId': '54782bfce4b086cb31d51dd5', 'status': 'ASSIGNED'}}}).pretty()

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" }] }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM