0

I'm using MongoDB with PHP's own driver and I have saved multiple arrays under main document. Structure looks like this:

{
 _id: 234234234324,
 accounts: {
    0: {
        enabled: 1,
        name: 'asdf'
    },
    1: {
        enabled: 0,
        name: 'gfsd'
    }
}

Accounts are removed and added by the user so I have no control over the array key. I need to somehow get all accounts that have enabled: 1. I tried array("accounts.enabled"=>1) but it doesn't work. And suggestions?

1 Answer 1

4

In your schema accounts isn't nested array, it's actually complex object, because of this array("accounts.enabled"=>1) will not work (you actually can check only particular element -> array("accounts.0.enabled"=>1)).

Solution of your problem can be schema redesign as follows:

{
 _id: 234234234324,
 accounts: [
    {
        enabled: 1,
        name: 'asdf',
        id: 0
    },
    {
        enabled: 0,
        name: 'gfsd',
        id: 1
    }]
}

If you will make above changes, your query will work.

Sign up to request clarification or add additional context in comments.

1 Comment

Ok thanks. I don't think it's worth the hassle to do schema redesign at this point. What I can do is to get all docs with accounts and then iterate and get enabled ones. Not very efficient but will work just fine in what we are doing.

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.