Achelon
Achelon

Reputation: 37

Transforming MongoDB query to Java with $elemMatch

I'm having a lot of trouble transforming my MongoDB Query into a Java one. I've tried both QueryBuilder and DBObject and can't manage to make it work.

This is my MongoDB Query:

db.getCollection('myCollection_v2').find({
    idCab:1,
    cab: {
        $elemMatch:{
            idCat: ObjectId("14567823123688")
        }
    },
    fMod: {
        $gte: ISODate("2017-04-04T00:00:000Z"),
        $lt: ISODate("2017-04-04T23:59:590Z")
    }
})

My DBOBject approach has been this and the problem that I get is that I cannot append(object, object) but append(string, object) so I don't know how should I structure it:

BasicDBObject query = new BasicDBObject(
            "idCab", "1")
            .append( new BasicDBObject(
                "cab", new BasicDBObject(
                        "$elemMatch", new BasicDBObject( 
                                "idCat", categoria ))))
            .append( new BasicDBObject(
                    "fMod", new BasicDBObject( "$gte", fechaInicio )
                        .append( "$lt", fechaFin )
                    )
            );

For a QueryBuilder I have this and the problem is that I didn't manage to make the part about the $elemMatch...

QueryBuilder query = new QueryBuilder().start().and(
            new QueryBuilder().start().put("idCab").is(String.valueOf(pIdPortal)).get(),
            new QueryBuilder().start().put("fMod")
                .greaterThan(fechaInicio).get(),
            new QueryBuilder().start().put("fMod")
                .lessThan(fechaFin).get();

Could you help me, please? I'm going from a 50-50 love/hate relationship with MongoDB to a 100 hate relationship...

Upvotes: 0

Views: 1291

Answers (1)

felix
felix

Reputation: 9285

your DBObject is not properly formed. Your trying to pass a BasicDBObject as key instead of passing a String . Just remove the two extra BasicDBObject like this :

   BasicDBObject query = new BasicDBObject(
            "idCab", 1)
            .append("cab", new BasicDBObject(
                    "$elemMatch", new BasicDBObject(
                            "idCat", categoria)))
            .append("fMod", new BasicDBObject("$gte", fechaInicio)
                    .append("$lt", fechaFin)
            ); 

Upvotes: 3

Related Questions