Reputation: 1202
What's an elegant way to set the query parameter so find() intentionally returns no documents?
Obviously I could just hardcode a query that I know would never return a result for my dataset. But that would be no fun.
Upvotes: 3
Views: 483
Reputation: 31
I have a similar concern in that I want to build queries based on conditional logic. I could write full BSON for each condition but I think it makes the code less readable. What I ended up doing was using AND with a filters list
List<Bson> filters=new ArrayList<>();
filters.add(eq("title", job.getTitle()));
filters.add(eq("companyName", job.getCompanyName()));
if (job.getPostingDate() != null) {
filters.add(eq("postingDate", job.getPostingDate()));
}
if(job.getMinYearlySalary()!=null){
filters.add(eq("minYearlySalary", job.getMinYearlySalary()));
}
if(job.getMaxYearlySalary()!=null){
filters.add(eq("maxYearlySalary", job.getMaxYearlySalary()));
}
if(job.getMinHourlySalary()!=null){
filters.add(eq("minHourlySalary", job.getMinHourlySalary()));
}
if(job.getMaxHourlySalary()!=null){
filters.add(eq("maxHourlySalary", job.getMaxHourlySalary()));
}
Bson query=and(filters);
CountOptions options = new CountOptions();
options.limit(1);
if (collection.countDocuments(query, options) > 0) {
containsJob = true;
}
What I did is not the OPs exact question. I think this using an empty list would return everything but I have not tested it and could see it also returning nothing. That being said this approach will not waste time with pointless comparisons and is at least an interesting starting point.
Upvotes: 0
Reputation: 13753
you won't gonna save negative _id
. So you can try:
db.collection.find({"_id":-1})
Upvotes: 3
Reputation: 7840
Query on _id
field like following use any one of this :
db.collectionName.find({"_id":0})
db.collectionName.find({"_id":""})
db.collectionName.find({"_id":null})
Upvotes: 3