如何使用 Java 仅从与特定过滤器匹配的 MongoDB 文档中获取

我的 MongoDB 文档是这样的:


"_id":"C\Users...\1.html"{

"data": Object[

        gambia:1

        estonia:1

        ...etc

        ]

}

我不知道我写的结构是否正确,所以这里有一张图片:

http://img4.mukewang.com/6358f035000159ed04830340.jpg

我的问题是我想从数据库中获取与给定特定单词匹配的所有文档。例如,如果用户输入“汽车”,我需要其数据中包含汽车一词的所有文档。但我找不到怎么做。


我试过什么?我试图获取与我知道它存在于第一个文档中的单词“gambia”匹配的第一个文档:


    MongoClient mongoClient = MongoClients.create();

    MongoDatabase database = mongoClient.getDatabase("motor");


    MongoCollection<Document> collection = database.getCollection("dictionary");

    String word = "gambia";

    Document myDoc = collection.find(Filters.eq("data", word)).first();

    System.out.println(myDoc);

但我得到一个空指针异常。


UYOU
浏览 106回答 1
1回答

慕丝7291255

您可以使用 mongodb 函数来实现这一点$exists。此函数告诉您确定的字段是否在您的集合中。例如:MongoCollection<Document> collection = database.getCollection("dictionary");String word = "gambia";DBObject query = new BasicDBObject("data." + word, new BasicDBObject(&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "$exists", true));Document myDoc = collection.find(query);System.out.println(myDoc);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java