-1

I'm trying to find out if an Object (document) exists in a collection.

Here's what I've tried but I'm stuck.

@DbTable(name = "websites")
private MongoCollection websitesTable;

private boolean isInTable(String url) {
    FindOne p = websitesTable.findOne("{url: #}", url);
    return false;
}

How do I check, if given url is already in the collection? Any help appreciated.

aioobe
  • 413,195
  • 112
  • 811
  • 826
user1924244
  • 135
  • 9
  • 2
    user1924244, This is not a help desk. It you are unable to take help from other similar questions, then this is not the right place to be. SO is for people that is really stuck with real problems, so please do not dictate what people should do and not do. – Jaques May 14 '15 at 09:02
  • @Jaques, who are you to tell what is a "real" problem and what is not? – aioobe May 14 '15 at 09:03
  • @user1924244, have a look at this document: [Checking if a document exists – MongoDB slow findOne vs find](https://blog.serverdensity.com/checking-if-a-document-exists-mongodb-slow-findone-vs-find/). It recommends the following command: `db.collection.find({_id: "myId"}, {_id: 1}).limit(1))`. – aioobe May 14 '15 at 09:05
  • @aioobe I already were there, but do not know how to do it. It puts me some errors. I dont know Java. I am PHP programmer, but company wants this from me and... – user1924244 May 14 '15 at 09:07
  • 2
    @aioobe Well, for starters as SO is moderated by the users, which includes Jacques. The read worthy document [How do I ask a good question](http://stackoverflow.com/help/how-to-ask) suggests research first. If OP had done proper research, writing the question would have been more work than solving the "problem" on his own. You might find [ESR](https://en.m.wikipedia.org/wiki/Eric_S._Raymond)'s excellent essay [How To Ask Questions The Smart Way](http://catb.org/~esr/faqs/smart-questions.html) interesting in that regard, too. – Markus W Mahlberg May 14 '15 at 09:13
  • 1
    @user1924244 So your root problem is that you are not a Java programmer. Be professional and clearly state that you can't fulfill that requirement in a proper way - it will take longer, you will make mistakes and the overall code quality most likely won't be production ready. – Markus W Mahlberg May 14 '15 at 09:18

1 Answers1

1

Try this:

return websitesTable.findOne("{url: #}", url)
                    .as(Map.class)
                    .iterator()
                    .hasNext();
aioobe
  • 413,195
  • 112
  • 811
  • 826
  • I changed it little: `Map website = websitesTable.findOne("{url: #}", url).as(Map.class);` and then `return website == null ? false : true;` and now it works! I don't know if it's allright, but it works like it would. – user1924244 May 14 '15 at 09:46
  • Great. Note that the return could be simplified as `return website != null;` – aioobe May 14 '15 at 09:55