Reputation: 329
I've got a collection with a number of documents with integer arrays. I'm trying to find if a setting/number exists in anywhere in the collection. In the shell it works fine:
> 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
But I can't make it work via the Java driver. But I can't figure out how to tell if the find actually found something.
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
}
}
I feel like I'm somehow making this harder than it should be. In the shell, it's a no-brainer. I'd really hate to have to iterate through each collection's documents checking for the existence of the number in the array but I've blown more time trying to find the "efficient" way than it would have taken to brute force it.
Upvotes: 0
Views: 354
Reputation: 3554
Basically, you have two different cases:
(a) Iterate through the collection, and be ready for every number of results. This is where you use find and the FindIterable which you declared in your question.
(b) Get the count, which is exactly the same as in your shell example:
col.count(<whateverfilter>)
By the way: you should really have a look at the utility classes Filters and Projections. Your code uses old and ugly style, that should not be necessary anymore with the 3.x series of the java driver.
Upvotes: 1