0

Using PHP and Mongo I would like to update the users availability but cannot figure it out. How can I structure my collection to be able to reference availability groups.steve.availability?

Below is the structure of my "groups" collection:

{
"_id": {
    "$oid": "524327d536b82c7c5c842f6d"
},
"group_id": "testing",
"password": "test",
"users": [
    {
        "username": "steve",
        "availability": "null"
    },
    {
        "username": "joeb",
        "availability": "null"
    }
]

}

1 Answer 1

1

If you want to reference it the way you've suggested: groups.steve.availability, you'd need to structure your documents more like below. (I'm not sure where groups is coming from).

This example would give you users.steve.availability by moving the user's name to a sub-field of the users field (users.steve).

{
"_id": {
    "$oid": "524327d536b82c7c5c842f6d"
},
"group_id": "testing",
"password": "test",
"users": {
    "steve": {
        "availability": "null"
    },
    "joeb" : {
        "availability": "null"
    }
}
}

Or, you could just create fields directly on the document:

{
"_id": {
    "$oid": "524327d536b82c7c5c842f6d"
},
"group_id": "testing",
"password": "test",
"steve": {
        "availability": "null"
},
"joeb" : {
        "availability": "null"
}
}

That would allow you to just use steve.availability.

If you're trying to do a query though, you'd be better off leaving it more like you had it originally:

"users": [
{
    "username": "steve",
    "availability": "null"
}]

So, you could write queries that were like:

db.groups.find({"users.username" : "steve" })
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for the detailed explanation. I am looking to query and update the availability of each user. Is it possible to query and update availability to yes, where group_id=testing and username=steve? Is it possible to do that either way? If so, which way do you recommend?
Probably storing them as an array would be best -- but it's hard to know without understanding a lot more about your requirements.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.