I've below mongoDB aggregation which is filtering tests array in my mongodb collection item.
Sample collection item : {,...tests:[ {} , {"someField":"yesIamHere"} ] }
Below query worked well and returned only tests collection which contains someField
db.getCollection('yourcollection')
.aggregate([
{"$match": {"tests.someField": {"$exists": true}}},
{ $project:{"tests": {"$filter": {"input": "$tests", "as": "item",
"cond": {"$ne": ["$$item.someField", undefined]}}}}
},
])
However,
While using java BasicDBObject is taking "undefined"
as string not JS undefined
BasicDBObject projectionFilterInput=new BasicDBObject("input","$tests")
.append("as", "item")
.append("cond",new BasicDBObject("$ne", Arrays.asList("$$item.someField","undefined")));
So, this interprets "cond": {"$ne": ["$$item.vidaptorCode", "undefined"]}}}}
"undefined" not undefined
. So, this doesn't filter the items as intended.
Is there any constant defined for this specific undefined
value in mongodb java driver base ? This is the main question.
Whoever curious...
Why am I not using ODM ?
Actually we do use Spring Data for MongoDB, but it doesn't support this aggregation cond
.
MatchOperation matchStage = Aggregation.match(new Criteria("tests.someField").exists(true));
ProjectionOperation projection = Aggregation.project("tests");
Aggregation aggregation
= Aggregation.newAggregation(matchStage, projection);
AggregationResults<LabConfiguration> output
= mongoTemplate.aggregate(aggregation, "yourcollection", YourClass.class);
Morphia ODM
I liked Morphia fluent syntax however they're using different annotations than Spring Data Mongo and its dependent MongoDB libs are different. In short, two ODM don't work together.
The biggest problem is for repository implementation you need to implement BasicDAO<C,K>
and it's not very practical, it's mongo oriented and Spring Data Mongo does great job with MongoRepository<C,K>
Projections filterProjection = projection(
"tests",
expression(
"$filter",
new BasicDBObject("input","$tests")
.append("as", "item")
.append("cond",new BasicDBObject("$ne", Arrays.asList("$$item.someField","undefined")))
)
);
Hence, I ended up with Mongo driver base syntax for this problem that's why I need to pass undefined
to BasiDBObject but not as a string covered by double quotes.
I'm also open to hear your overall advices. What we have now is QueryDSL
and Spring Data for MongoDB
.