简体   繁体   中英

how to convert epoch time stored in nested field to date mongodb

I have a nested field msgs.crtDtTm inside a mongodb which has epoch date ( 1554120000 )stored as string. I need to convert msgs.crtDtTm to Date format to apply $gte (which is not working in String format).

cond: { $gte: [ "$msg.crtDtTm", "1554120000" ] }

I tried this but greater than operation not performed. It is returning all the nested elements without filtering.

You can convert string to date by this command :

new Date("1554120000")

Like this :

db.YourCollection.find({"created_at" : { $gte : new Date("1554120000") }});

in your example :

cond: {$msg.crtDtTm : { $gte:  new Date("1554120000") }}

Let me know the result please .

This link is also useful

Once your time april 1,2019 being converted into ms and then to type of string in your code, it would be easy that way(as converting one element vs n values in DB - altogether it might be easy for that format to be converted into ms in code), then use this query to retrieve elements that match your criteria :

db.yourCollection.aggregate([
    {$match: {'msgs.crtDtTm': {$gt: '1554120000'}}},
    {$addFields: {
        msgs: {$filter: {
            input: '$msgs',
            as: 'msg',
            cond: {$gt: ['$$msg.crtDtTm', '1554120000']}
        }}
    }}
])

You could achieve similar using $unwind on msgs & then $match finally $group or $match to start with, which ever is feasible you can go ahead. Something like this :

db.yourCollection.aggregate([{
    $match: {
        'msgs.crtDtTm': { $gt: '1554120000' }
    }
},
{ $unwind: "$msgs" },
{
    $match: {
        'msgs.crtDtTm': { $gt: '1554120000' }
    }
}, { $group: { _id: '$_id', msgs: { $push: '$msgs' }, docs: { $first: '$$ROOT' } } }, { $addFields: { 'docs.msgs': '$msgs' } }, { $replaceRoot: { newRoot: '$docs' } }])

Lastly, It would be a better idea if you can store the same format which will be used to query.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM