Hi everyone,
I’m fascinated, studying MongoDB. But still struggling with query sintaxes and pipelines. I’m implementing it a project. Almost everything I was able to solve by myself, but for a harder task, tried for many hour to code the following query, but with no success. So I came here to ask for help. I will give the details:
- In a quiz game, players will get a daily question to answer.
- Server will assign a random question to each players everyday in a cron-job function.
- Each player document have a nested object with all question status on it’s document.
- As a condition, It need to filter all questions with “not-attempted” status from each player, pick randomly one question and change it’s status to “assigned”.
- Need to run this task for all players, but just randomly update one object item status to “assigned”.
When I began to build this query, it was working, but when I try to use any operator or subfunction in pipeline(count,sort,rand,sample etc), it returns me a sort of errors. Maybe syntax, or maybe there a simpler way to do this, idk…
Here is a document structure:
{
"_id": "633360536b4cab132e2fc218",
"username": "Alberto Silva",
"role": "player",
"questionList": [
{
"questionid": "A0",
"time": null,
"answered": null,
"score": null,
"status": "not-attempted",
"startDate": null,
"respondedDate": null
},
{
"questionid": "A1",
"time": null,
"answered": null,
"score": null,
"status": "not-attempted",
"startDate": null,
"respondedDate": null
},
{
"questionid": "A2",
"time": null,
"answered": null,
"score": null,
"status": "not-attempted",
"startDate": null,
"respondedDate": null
},
],
"team": "0"
}
And here is the current buggy / incomplete query:
db.users.updateMany(
{
role: "player"
},
[
{
$set: {"questionList.$[tocount].availablequestions": { $count: {"$questionList.$[tocount].questionList" : "not-attempted"} }}
},
{
$set: {"questionList.$[index].status": "assigned"}
},
],
{
arrayFilters: [
{
"elem.tocount": {
$eq: "not-attempted"
},
"index._(somehow_get_one_pipelinearray_index_randomly)": {
$floor: {
$multiply: [ { $rand: {} }, "$questionList.availablequestions" ]
}
},
}
],
}
)
Can anyone give me a light on how to proceed on it?
If someone could give me insights on how to do that, It would be appreciated.
Thanks