繁体   English   中英

如何使用Java从Mongodb集合中检索arraylist的元素?

[英]How to retrieve an element of an arraylist from a Mongodb collection using java?

我有以下代码,我的目的是检索具有给定标签的文档。

String myText = "It is the first #example and is very #important";
ArrayList<String> tags = textProcessor.getTags(myText);

 try {
            MongoClient mongo = new MongoClient("localhost", 27017);
            DB db = mongo.getDB("myFirstDatabase");

            DBCollection table = db.getCollection("firstCollection");
            BasicDBObject document = new BasicDBObject();
            document.put("Text", myText);
            document.append("tags", tags);
            table.insert(document);

            /**** Find and display ****/
            BasicDBObject searchQuery = new BasicDBObject();
            searchQuery.put("tags", "#important");

            DBCursor cursor = table.find(searchQuery);

            while (cursor.hasNext()) {
                System.out.println(cursor.next());
            }

它不起作用,因为tags是一个数组,并且我正在数组中搜索一个element 如何直接检索具有给定标签(在这种情况下为“重要”)的文档? 我知道我可以提取所有文档的所有标签,然后在循环中进行比较。 但我想直接这样做。

同时,我对mongodb完全mongodb 如果有更好的方法在数据库中插入标签(这样,检索起来就更容易了),我将不胜感激。

提前致谢,

可以通过单个字符串查询查询Mongodb列表就好了,您应该检查textProcessor.getTags并检查mongodb中的数据。 我还建议您使用spring-data-mongodb,因为它更简单易学。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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