0

I have a mongodb data base like this:

{
    "_id" : ObjectId("530d24150fef5d9b065909ca"),
    "data" : "object 1",
    "my_array" : [
        {"arraydata" : "1"},
        {"arraydata" : "2"}
    ]
}
{
    "_id" : ObjectId("530d24150fef5d9b065909ca"),
    "data" : "object 2",
}
{
    "_id" : ObjectId("530d24150fef5d9b065909ca"),
    "data" : "object 3",
    "my_array" : [{"arraydata" : "1"}]
}

I want to make a query which only returns document that contains some data in my_array, in this case it'd returned the first and the last one.

I understood that $where statement is slow, so I want to get a better approach.

Thanks in advance.

1

2 Answers 2

0

If you know that the array never exists but is empty, as in your example data, then the following is simpler:

db.c.find({my_array: {$exists: true}})

However, if you want to filter out documents where the array exists but is empty, they your answer is good.

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

1 Comment

I think this answer is better than mine, so I'll accept it. Thanks.
0

Got it using:

db.document.find({'my_array.0': {$exists: true}})

Is there a better approach?

Comments

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.