which looks in the field mqt_data.user_transaction_time of type string for the literal “2018 - 02”
Hi Shivaji,
Could you elaborate on what you’re trying to achieve with :
If you’re just trying to find documents where mqt_data.user_transaction_time field has value of “2018 - 02” then you can just use:
{ "$match" : { "mqt_data.user_transaction_time" : "2018 - 02" } }
Note that the format of $match equality condition is { <field1>: <value1>, ... }, and you’re example is missing the field name.
Regards,
Wan.
The field, mqt_data.user_transaction_time, is of type string but has the same format as an ISODate.
Hi Shivaji,
You should consider converting the values to Date. Store the values in the format the data is supposed to represent. If the field is stored in Date then you could use $redact, example:
db.coll.aggregate([{"$redact":{
"$cond":[
{"$and":[
{"$eq":[ {"$year" :"$mqt_data.user_transaction_time"}, 2018] },
{"$eq":[ {"$month":"$mqt_data.user_transaction_time"}, 2] },
]},
"$$KEEP", "$$PRUNE"]
}}
]);
How can I correct the $match syntax since the “field” that I want to compare with requires just the date component parts of YY - MM (string type and not date type).
If it’s String i.e. {"user_transaction_time": "2018-08-20T08:52:55.393Z"}, you can use $regex:
db.coll.aggregate([{"$match":{"mqt_data.user_transaction_time": {"$regex": "^2018-02"}}}]);
In MongoDB v3.6+, you can use $dateFromString to convert the value from string into Date then use the $redact example above:
db.coll.aggregate([
{"$addFields":{
"newdate": {
"$dateFromString": {"dateString":"$mqt_data.user_transaction_time"}
}}},
{"$redact":{
"$cond":[
{"$and":[
{"$eq":[ {"$year":"$mqt_data.user_transaction_time"}, 2018] },
{"$eq":[ {"$month":"$mqt_data.user_transaction_time"}, 2] },
]},
"$$KEEP", "$$PRUNE"]
}}
]);
You may also find Aggregation Pipeline Optimization a useful reference.
Using MongoDB 3.2
Please note that MongoDB v3.2 has reached it’s end of life last month (September 2018). If this is a new deployment please see current stable MongoDB version.
Regards,
Wan.