Reputation: 4574
I'm new to MongoDB. I'm using laravel-mongodb.
I have a document in tree structure. I need to get documents for a specific year. Here is the image of how my data is:
I need to select all documents that have the period 2017. my problem is that the period is a field of type object. And the value is the index. Does anyone know how I can do this?
Upvotes: 1
Views: 268
Reputation: 13103
You need to use $exists operator
db.collection.find({ "periodos.2017" : { $exists : true } })
Upvotes: 0
Reputation: 17915
You can try below query :
db.collection.aggregate([
/** As we need to filter on key but not on key's value,
* So convert periodos object to an array which makes {k : 2017, v : value of 2017} etc.. */
{
$addFields: {
periodos: {
$objectToArray: "$periodos"
}
}
},
/** Filter docs to check periodos has 2017 */
{
$match: {
"periodos.k": "2017"
}
},
/** convert periodos array back to object to its original type */
{
$addFields: {
periodos: {
$arrayToObject: "$periodos"
}
}
}
])
Test : MongoDB-Playground
Upvotes: 1