如何使用java编写mongodb查询
db.Tasks.find({'assignedMember': {'$elemMatch': {'userId': '54782bfce4b086cb31d51dd5', 'status': 'ASSIGNED'}}}).pretty()
答案 0 :(得分:1)
以下是OP中查询的Java代码。您可能需要在以下代码中相应地更改集合名称和数据库名称。
MongoDB Java驱动程序版本= 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();
}
}
用于测试此代码的测试文档: -
{
"_id" : ObjectId("583805ac204e6a612ebaf7e0"),
"assignedMember" : [
{
"userId" : "54782bfce4b086cb31d51dd5",
"status" : "ASSIGNED"
}
]
}
<强>输出: - 强>
{ "_id" : { "$oid" : "583805ac204e6a612ebaf7e0" }, "assignedMember" : [{ "userId" : "54782bfce4b086cb31d51dd5", "status" : "ASSIGNED" }] }