I would like to query a one/more matching fields of an array elements(can include subdocuments too) that is into document.
For example:
My collection includes documents below:
{
"_id": 1,
"index": 1,
"elements":[
{
"name":"test",
"date":"Mon Sep 01 01:00:00 EEST 2014" ,
"tag":1
},
{
"name": "test2",
"date": "Mon Sep 01 01:00:00 EEST 2014",
"tag": 2
},
{
"name": "test",
"date": "Mon Sep 01 02:00:00 EEST 2014",
"tag": 3
}
]
},
{
"_id":2,
"index":2,
"elements":[
{
"name":"test",
"date":"Mon Sep 01 01:00:00 EEST 2014" ,
"tag":1
},
{
"name": "test2",
"date": "Mon Sep 01 01:00:00 EEST 2014",
"tag":2
},
{
"name":"test",
"date":"Mon Sep 01 01:10:00 EEST 2014",
"tag":3
}
]
},
{
"_id": 3,
"index": 3,
"elements": [
{
"name": "test",
"date": "Mon Sep 01 01:00:00 EEST 2014",
"tag":1
},
{
"name": "test2",
"date": "Mon Sep 01 01:00:00 EEST 2014",
"tag":2
},
{
"name": "test",
"date": "Mon Sep 01 01:10:00 EEST 2014",
"tag":3
}
]
}
I want my query result to return me a document like below:
{
"_id":1,
"index": 1,
"elements":[
{
"name":"test",
"date":"Mon Sep 01 02:00:00 EEST 2014" ,
"tag":3
}
]
}
To provide this I wrote a query
Date dCriteria = new SimpleDateFormat("dd/MM/yy HH:mm:ss").parse("01/09/2014 05:00:00");
Query find = new Query( Criteria.where("index").is(3) ); //To find matching documents
find.fields().elemMatch(
"elements",
Criteria.where("name").is("test").and("date").gte(dCriteria)));
mongotemplate.findOne( find, Document.class );
Which means in MongoDB shell command as:
db.collection.find(
{ "index": 3 },
{ "elements": {
"$elemMatch": {
"name": "test",
"date": {
"$gte": { "$date":"2014-09-01T02:00:000Z" }
}
}
}
)
But it return the following result:
{
"_id": 0,
"index": 0,
"elements":[
{
"name": "test",
"date": "Mon Sep 01 01:00:00 EEST 2014",
"tag":1
}
]
}
It is ok to omit _id and index fileds but it returns first macting element of array due to matching criteria , either matching "name":"test" or "date" is greater than equal dCriteria, but what I want is to match both criterias at the same time.
To make this I must use $elemMatch operator to query exatcly matches more than one field at the same time of an array element. But I have no idea how to use its syntax in my projection.