Since every collection in mongodb has a default index on the _id column, I wanted to leverage it for my scenario as below.
I have my collection as below,
{
"_id":{
"timestamp" : ISODate("2016-08-24T23:22:20.201Z"),
"departmentname" : "sales",
"city":"NJ"
}
//Other fields in my collection
}
With this structure I am able to query as below,
db.getCollection('test').find(
{
"_id" : {
"timestamp" : ISODate("2016-08-21T23:22:20.201Z"),
"departmentname" : "sales",
"city":"NJ"
}
}
)
But, when I query by one or more fields in which are part of _id column as below,
db.getCollection('test').find(
{
"_id" : {
"timestamp" : ISODate("2016-08-21T23:22:20.201Z")
}
}
)
(OR)
db.getCollection('test').find(
{
"_id" : {
"departmentname" : "sales"
}
}
)
(OR)
db.getCollection('test').find(
{
"_id" : {
"departmentname" : "sales",
"city":"NJ"
}
}
)
I do not see any documents returned
When I checked with .explain() I see that it has used Index but did not find any documents.
Also, I would like to do date range queries on timestamp field along with query on one or more fields in the _id column like below,
db.getCollection('test').find(
{
"_id.timestamp" : {
"$gte": ISODate("2011-08-21T23:22:20.201Z")
},
"_id.departmentname" : "sales"
}
)
But, I do not see any documents returned. When I run .explain() I see it has used colscan and not index.
Can someone help me on the right way to query by one or more fields on my _id column.
Thanks,
Sri
You can try following query, in first case:-
db.getCollection('test').find(
{
"_id.timestamp" : ISODate("2016-08-21T23:22:20.201Z")
})
And this for multiple fields:
db.getCollection('test').find(
{
"_id.timestamp" : ISODate("2016-08-21T23:22:20.201Z"),
"_id.departmentname" : "sales",
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With