1.15.2 MongoDB - Check if value exists in a field.

Discussion in 'Spigot Plugin Development' started by Foreignlos, Jan 17, 2020.

  1. Hey everyone, In the last few days I've been struggeling about how to solve this:
    Here's one document from a MongoDB database:
    Code (Text):

    Name: Example
    Owner: John
         1: Jason
         2: Rob
         3: Carey
    How would I go about checking if let's say the value "Rob" is in the Players field?
    I have his name, But I don't know if he exists in the database or not, How can I check if he is in a Players field?
    Also, let's say it did found him in the database, Can I get let's say the Owner only by knowing Rob's value?
    Might sound simple but I'm really new to MongoDB and I can't seem to find many documentations/tutorials online with Java.
  2. I've already seen this documentation but I can't understand it, Ok I understand this function finds the value, but how do I check if it found it? when I try to make an if statement it'd say it's a FindIterable type and not Boolean, so this FindIterable thing doesn't really help me. because I want to check if it found it.
  3. Well I already know Count() is deprecated because I researched before, and countDocuments() is not what I'm looking for, this only counts how many documents there are with this information, I want to get another piece of information by a known piece of information.
    As I've stated in my question - I couldn't find any proper documentations for this, so this is the reason I've asked here.
    And trust me - I've done more research than I thought I should, and the closest thing I've found was a post from like 6 years ago that is very hard to understand/probably is not what I need.
  4. My apologies didn't notice you had a two part question. Could you post the link to the post you found?
  5. Do you know how a SELECT works in standard SQL? The find() function is essentially a filter in the same way SELECT uses a WHERE clause to filter rows. You get an MongoIterable with the documents that match the condition (eg “Players contains Rob”).

    It’s been a while since I’ve used Mongo but theoretically the first() function should return null if the result set is empty, so check that to see if there are any entries matching your filter. Since the MongoIterable is just the documents, you can manipulate the filtered entries in whatever way you like simply by using a for-each loop over it.
  6. Thanks for this,
    But what if I have a multiple files containing the same information? first() would only get the first one it found.
  7. I meant that first() can be used to check if there is anything in the returned iterable. Like I mentioned, you can use a for-each over the MongoIterable to go through each document. There are multiple other ways to iterate over it, you can simply look at the JavaDocs if you’re interested.