Home > database >  Fetch fields starting with 2 particular substring in mongodb using springboot?
Fetch fields starting with 2 particular substring in mongodb using springboot?

Time:05-27

I'm trying to find all the documents with first name starting with Ram or Shyam. I tried the following which actually worked in mongoDb

db.collection.find({
  $or: [
    {
      name: {
        $regex: "^Ram"
      }
    },
    {
      "name": {
        "$regex": "^Shyam"
      }
    }
  ]
})

I got around count of 4k documents with this find.

Now when I tried to convert this mongo shell query into java. Things do work but only name starting with Shyam get filtered. As a result the count also decreases to 2k.

Can someone please look at the below code and tell me why is it happening? Why things are working in mongodb and not in java.

Java Equivalent Code --

        MongoDatabase database = mongoClient.getDatabase("Friends");
        MongoCollection<Document> collection = database.getCollection("Friend");
        BasicDBObject filter = new BasicDBObject("$or", Arrays.asList
            (new BasicDBObject("name", new BasicDBObject("$regex", "^Ram")).append("name", new 
             BasicDBObject("$regex", "^Shyam"))));
        collection.find(filter).forEach((Consumer<Document>) doc -> {
                 // some java function
    }

CodePudding user response:

I figured out. There is just one some thing as $or operator always take array In my java code I have converted it into array but just forgot that there is no need to append .

The solution will be --

BasicDBObject filter = new BasicDBObject("$or", Arrays.asList
            (new BasicDBObject("name", new BasicDBObject("$regex", "^Ram")),new BasicDbObject("name", new 
             BasicDBObject("$regex", "^Shyam"))));
        collection.find(filter).forEach((Consumer<Document>) doc -> {
                 // some java function
    }

CodePudding user response:

As per your mongo query, you need to match against name field but not on id field. That's the mistake

BasicDBObject filter = new BasicDBObject("$or", Arrays.asList
    (new BasicDBObject("name", new BasicDBObject("$regex", "^Ram"))
    .append("id", new //Here is the mistake
           BasicDBObject("$regex", "^Shyam"))));

It should be

    BasicDBObject filter = new BasicDBObject("$or", Arrays.asList
        (new BasicDBObject("name", new BasicDBObject("$regex", "^Ram"))
       .append("name", new BasicDBObject("$regex", "^Shyam"))));
  • Related