0

I have the following code and my aim is to retrieve the documents which have the given tags.

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());
            }

It does not work, because the tagsis an array and I am searching for an element in the array. How can I retrieve the documents which have the given tag (in this case "important") directly? I know that I can extract all the tags of all documents and then compare them in a loop. But I would like to do that directly.

In the meantime, I am completely new to mongodb. If there is a better way to insert tags in the database (so that, its retrieving is easier), I would be grateful to know.

Thanks in advance,

3
  • it should be working if you find it using single string "#important" even though the tags is a list in mongodb. are you sure the textProcessor.getTags is correct? could you check the data in the mongodb and is it correctly inserted already? Commented Jun 25, 2019 at 9:05
  • @NaFelixWimpyWijaya Thanks a lot. You're right. I had already removed the # from the beginning of the tag. It means searchQuery.put("tags", "important"); was the correct way to find it. Could you please write your comment as an answer, so that I can mark it as the correct answer? Commented Jun 25, 2019 at 9:14
  • yes, and for addition, querying inner list in mongodb is good and will be working quite fast, perfomance wise. It's one of the best feature from nosql that sql doesn't have. I've posted the answer, thanks! Commented Jun 25, 2019 at 9:20

1 Answer 1

1

Mongodb list can be queried through a single string query just fine, you should check the textProcessor.getTags and check the data in the mongodb. I also suggest you to use spring-data-mongodb since it is much simpler and easier to learn.

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.