2

I have the following query which I am trying to implement in Java (I am using 3.4.2 mongo-java driver) :

Json:

     {
      "_id" : "Team:2334918",
      "fieldName" : [
                "Delivery",
                "Support"
            ],
      "isDeleted" : false
      }

Here the query:

  db.myCollection.find({$nor: [{“fieldName”: {$exists: false}},{“fieldName”:{$size:0}}]})

I have written the following code to implement the above query:

    MongoClient mc = ctm.getMongoConn();
     db = ctm.getDatabase(mc);
     col = db.getCollection(collectionName);

    BasicDBObject searchObject = new BasicDBObject();
    List<BasicDBObject> searchArguments = new ArrayList<BasicDBObject>();

    searchArguments.add(new BasicDBObject("fieldName",new BasicDBObject("$exists",false)));
    searchArguments.add(new BasicDBObject("fieldName",new BasicDBObject("$size",0)));
    searchObject.put("$nor", searchArguments);

    MongoCursor<Document> curs = (MongoCursor<Document>) col.find(searchObject);

    while (curs.hasNext()){

             Document doc = curs.next();
             Object name1 = doc.get("fieldName");

             System.out.println(name1.toString());
             j++;
         }

I am getting the following error while running:

java.lang.ClassCastException: com.mongodb.FindIterableImpl cannot be cast to com.mongodb.client.MongoCursor
Saurabh
  • 930
  • 2
  • 17
  • 39
  • 2
    Try `MongoCursor curs = col.find(searchObject).iterator();` Also you are mixing Document (3.x) and BasicDBObject (2.x). You can replace your search builder with `Filters filters = Filters.nor(Filters.exists("fieldName"), Filters.size("fieldName", 0);` – s7vr Jan 10 '18 at 16:52
  • thanks @Veeram, it worked – Saurabh Jan 10 '18 at 17:03

2 Answers2

1

Replace this:

MongoCursor<Document> curs = (MongoCursor<Document>) col.find(searchObject);

while (curs.hasNext()) {

}

With this:

FindIterable<Document> docs = col.find(searchObject);

for (Document d : docs) {

}

The suggestion from @Veeram (in the comments above) is correct too.

glytching
  • 44,936
  • 9
  • 114
  • 120
1

Try

MongoCursor<Document> curs = col.find(searchObject).iterator(); to get cursor.

You don't have to get hold of cursor. You can use the methods provided in the FindIterable which iterates the cursor for you. example at the end.

Also you are mixing Document (3.x) and BasicDBObject (2.x). You can replace your search builder with

Filters searchObject = Filters.nor(Filters.exists("fieldName"), Filters.size("fieldName", 0);
FindIterable<Document> curs =  col.find(searchObject);
curs.forEach();

More info here by the author.

s7vr
  • 73,656
  • 11
  • 106
  • 127