1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

  2. Anuncie Aqui ! Entre em contato fdantas@4each.com.br

[Python] pymongo group by year based on subdocument date

Discussão em 'Python' iniciado por Stack, Março 13, 2025.

  1. Stack

    Stack Membro Participativo

    I have mongodb document like

    [
    {
    _id: ObjectId('67cfd69ba3e561d35ee57f51'),
    created_at: ISODate('2025-03-11T06:22:19.044Z'),
    conversation: [
    {
    id: '67cfd6c1a3e561d35ee57f53',
    feedback: {
    liked: false,
    disliked: true,
    copied: true,
    created_at: ISODate('2025-03-11T06:27:48.634Z')
    }
    },
    {
    id: '67cfd77fa3e561d35ee57f54',
    feedback: {
    liked: true,
    disliked: false,
    copied: false,
    created_at: ISODate('2025-03-11T06:28:25.099Z')
    }
    },
    { id: '67d009f1a3e561d35ee57f5a', feedback: null },
    { id: '67d009f8a3e561d35ee57f5b', feedback: null }
    ]
    },
    {
    _id: ObjectId('67d00aeaa3e561d35ee57f5d'),
    created_at: ISODate('2025-03-11T10:05:30.848Z'),
    conversation: [
    { id: '67d00af7a3e561d35ee57f5f', feedback: null },
    { id: '67d00afaa3e561d35ee57f60', feedback: null }
    ]
    }
    ]


    Where main document has conversation sub document. I want to know how many likes, dislikes and copied data are there in each year.

    I tried to get year from the conversation.feedback.created_at using $dateToString opeartor.

    pipeline = [{'$match': {'conversation.feedback.copied': True}},
    {'$group': {'_id': {'$dateToString': {'format': '%Y',
    'date': '$conversation.feedback.created_at'}},
    'total_copied': {'$sum': 1}}}]


    but it gives error

    OperationFailure: PlanExecutor error during aggregation :: caused by :: can't convert from BSON type array to Date, full error: {'ok': 0.0, 'errmsg': "PlanExecutor error during aggregation :: caused by :: can't convert from BSON type array to Date", 'code': 16006, 'codeName': 'Location16006'}


    What I am expecting out as

    {
    "2025": {
    "total_liked": 1,
    "total_disliked": 1,
    "total_copied": 1
    }
    }


    How to convert the datetime object to Year and combine the total counts for 3 parameter?

    Continue reading...

Compartilhe esta Página