我想获取字段下载不存在的所有文档
find{ "download" : {$exists: false}}
对于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());
}
我的改编是
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())
存在线不起作用:
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
现在没有任何线索正确适应,因为我的查询在shell中工作,而使用UMongo,转移到java似乎不那么容易看到。
答案 0 :(得分:7)
你使用
collection.find(query,field);
作为find方法的第二个参数的DBObject用于指示要返回的结果文档的哪些属性。它有助于减少网络负载。
在您的示例中,您尝试将$ exists子句放入field
DBObject中。那不行。
第二个参数对象只能包含属性值1(包括此属性)或0(不包括)。
将其放入名为query
的第一个DBObject中。
答案 1 :(得分:2)
您可以使用DBCollection通过JAVA API执行此操作
public List<BasicDBObject> Query(String collection, Map<String, String> query, String... excludes) {
BasicDBObject bquery = new BasicDBObject(query);
BasicDBObject bexcludes = new BasicDBObject(excludes.length);
for (String ex : excludes) {
bexcludes.append(ex, false);
}
return db.getCollection(collection, BasicDBObject.class).find(bquery).projection(bexcludes)
.into(new ArrayList<BasicDBObject>());
}
答案 2 :(得分:2)
我们需要指定两件事。
第一:
collection.find(query,field);
以上命令不是来自MongoDB Java驱动程序。 这意味着我们只能在mongo shell(或mongo Compass)中运行,而不能在Java中运行。
第二: 限制Java中的字段,您可以像下面的代码一样使用projection()
find(queryFilter)
.projection(fields(include("title", "year"),exclude("_id")))
完整示例:
Bson queryFilter = eq("cast", "Salma Hayek");
//or Document queryFilter = new Document("cast", "Salma Hayek");
Document result =
collection
.find(queryFilter)
//.limit(1) if you want to limit the result
.projection(fields(include("title", "year"),exclude("_id")))
//or .projection(fields(include("title", "year"), excludeId()))
//or .projection(new Document("title", 1).append("year", 1))
.iterator()
.tryNext();