MongoDB Java驱动程序 - 在查询查询中使用存在投影

Duk*_*ing 3 java mongodb bson mongo-java

我想获得不存在字段下载的所有文档

find{ "download" : {$exists: false}}
Run Code Online (Sandbox Code Playgroud)

对于Java,我找到了一个例子:

  BasicDBObject neQuery = new BasicDBObject();
  neQuery.put("number", new BasicDBObject("$ne", 4));
  DBCursor cursor = collection.find(neQuery);

  while(cursor.hasNext()) {
    System.out.println(cursor.next());
  }
Run Code Online (Sandbox Code Playgroud)

我的改编是

      BasicDBObject field = new BasicDBObject();
      field.put("entities.media", 1);
  field.put("download", new BasicDBObject("$exists",false));
  System.out.println("Start Find");
  DBCursor  cursor = collection.find(query,field);      
      System.out.println("End Find Start Loop ALL 100k");
   int i = 1;
                while(cursor.hasNext())
Run Code Online (Sandbox Code Playgroud)

存在线不起作用:

Exception in thread "main" java.lang.reflect.InvocationTargetException
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:616)
        at org.eclipse.jdt.internal.jarinjarloader.JarRsrcLoader.main(JarRsrcLoader.java:58)
Caused by: com.mongodb.MongoException: Unsupported projection option: $exists
        at com.mongodb.MongoException.parse(MongoException.java:82)
        at com.mongodb.DBApiLayer$MyCollection.__find(DBApiLayer.java:314)
        at com.mongodb.DBApiLayer$MyCollection.__find(DBApiLayer.java:295)
        at com.mongodb.DBCursor._check(DBCursor.java:368)
        at com.mongodb.DBCursor._hasNext(DBCursor.java:459)
        at com.mongodb.DBCursor.hasNext(DBCursor.java:484)
        at ImgToDisk.main(ImgToDisk.java:61)
        ... 5 more
Run Code Online (Sandbox Code Playgroud)

它现在没有任何线索,正确的适应将是,因为我在shell中使用UMongo进行查询,转移到java似乎不那么容易看到.

rom*_*oll 7

你用

collection.find(query,field);
Run Code Online (Sandbox Code Playgroud)

作为find方法的第二个参数的DBObject用于指示要返回的结果文档的哪些属性.它对减少网络负载很有用.

在您的示例中,您尝试将$ exists子句放入fieldDBObject中.那不行.第二个参数对象只能具有属性值1(包括此属性)或0(排除).

把它放到第一个调用的DBObject中query.

另见这里这里