我有一个包含多个带有整数数组的文档的集合。我正在尝试查找集合中任何地方是否存在设置/数字。在外壳中可以正常工作:
> db.col.find({ settings: { $elemMatch: { $eq : 310403 } } }).count()
1
> db.col.find({ settings: { $elemMatch: { $eq : 310403 } } },{_id:1})
{ "_id" : 897 }
> db.albums.find({ images: { $elemMatch: { $eq : 310404 } } }).count()
0
但是我无法通过Java驱动程序使它起作用。但是我不知道如何辨别发现是否真的找到了东西。
FindIterable<Document> checkForSetting;
for (int i = 0; i < 1000000; i++) {
checkForSetting = col.find(new Document("settings",new Document("$eleMatch",new Document("$eq",i)))).projection(new Document("_id",1));
if ( null, empty, not found,etc) {
...do something
}
}
我觉得我在某种程度上使它比应有的难度更大。在外壳中,这是理所当然的。我真的很讨厌不得不遍历每个集合的文档以检查数组中数字的存在,但是我花了更多的时间来寻找“有效”的方法,而不是强行使用它。
最佳答案
基本上,您有两种不同的情况:
(a)遍历集合,并为每种结果做好准备。在这里使用find和在问题中声明的FindIterable。
(b)获取计数,该计数与您的shell示例中的计数完全相同:
col.count(<whateverfilter>)
顺便说一句:您应该真正了解实用程序类Filters和Projections。您的代码使用的是旧的丑陋的样式,对于Java驱动程序的3.x系列来说,这不再是必须的。