MutateIn Java SDK modify subdocument values

I want to log information about logins to the app.
My document looks something like this

[
{
“month”: “09-21”,
“login”: [
{
“id”: “user1”,
“count”: 2
},
{
“id”: “user2”,
“count”: 6
}
]
}
]

Here’s the scenario, a user logs in. based on his “id” and the current month of the year I will to update the document.
If there’s already data about him in this month then icrement (exemple 09-21 , user 1)
if not insert into the document.(09-21 someNewUser).

I read the documentation but I didn’t really help and I also looked for similar questions but none was helpful.

thanks in advance

Hi @elmk93
I think you’ll need to refactor your data model to support this, to:

"months":{
    "09-21":{
        "logins":{
              "user1":{"count": 2}
        }
    }
}

Now something like this should work, though admittedly I haven’t tested it:

MutateInResult result = collection.mutateIn("doc-id", Collections.singletonList(increment("months.09-21.logins.user1.count", 1).createPath()));

You may find the section on Sub-Document counter operations here Sub-Document Operations with the Java SDK | Couchbase Docs useful.

1 Like

Thanks it works ! I appreciate it .
Can you please just tell me in the case of the data model you suggested, how can I count logins for a specific month.

select count(logins) as compte from bucket stats
UNNEST OBJECT_VALUES(stats.months) AS months
UNNEST OBJECT_VALUES(months.logins) AS logins
where meta(stats).id = ‘monthly-stats’ and months = ‘09-2021’;

Without the last condition “months = ‘09-2021’;” it works but doesn’t work with that condition (I suppose it’s a syntax thing but I don’t know how should I do it ) :confused:
thanks in advance :slight_smile:

Sorry, N1QL isn’t my forte - perhaps someone else can suggest the correct syntax. Personally I would fetch the document via KV and do the calculation in code.

No worries, thank you for your help.