Dot notation to retrieve array element by position FAILS

284 views
Skip to first unread message

Glenn

unread,
Sep 22, 2010, 3:04:20 PM9/22/10
to mongodb-user
Hi, I'm trying to access an element of an Array by the position (index
in the array) using dot-notation. The mongo docs seem to claim that
this is possible. However, when I try to do this, I get no result
back. Here is my test case in the mongo console (the first command
shows the whole array and verifies that there is an element in it,
then the second command fails to access it):

> db.foo.find({"key":"12345"}, {"array_field": 1})
{ "_id" : ObjectId("4c9a41204cb16aa4fe28c4cc"), "array_field" : [
{
"bar" : "data",
"bam" : "more data",
}
] }

> db.foo.find({"key":"12345"}, {"array_field.0":1})
{ "_id" : ObjectId("4c9a41204cb16aa4fe28c4cc"), "array_field" :
[ { } ] }

Am I doing something wrong?

Michael Dirolf

unread,
Sep 22, 2010, 3:11:44 PM9/22/10
to mongod...@googlegroups.com
I think there's some inconsistency there with how dot notation works
for query documents and in a projection. In your case you should be
able to use $slice to only get back certain indexes from an array.

> --
> You received this message because you are subscribed to the Google Groups "mongodb-user" group.
> To post to this group, send email to mongod...@googlegroups.com.
> To unsubscribe from this group, send email to mongodb-user...@googlegroups.com.
> For more options, visit this group at http://groups.google.com/group/mongodb-user?hl=en.
>
>

Glenn

unread,
Sep 22, 2010, 3:21:43 PM9/22/10
to mongodb-user
Michael, thanks for the quick response.
So, I was successful with this command (with the _id field also
specified):

> db.foo.find({"key":"12345"}, {_id:1, array_field:{$slice:[0,1]}})

But this seems incredibly broken, since it's totally separate from any
other nested field access. It will mean I'll have to totally jerry-
rig my custom php ORM class to handle these special cases. Is this a
known problem with Mongo, and are they going to fix it?

On Sep 22, 12:11 pm, Michael Dirolf <m...@10gen.com> wrote:
> I think there's some inconsistency there with how dot notation works
> for query documents and in a projection. In your case you should be
> able to use $slice to only get back certain indexes from an array.
>

Michael Dirolf

unread,
Sep 22, 2010, 3:23:04 PM9/22/10
to mongod...@googlegroups.com
You can open a case to handle array indexes in projections on jira.mongodb.org
Reply all
Reply to author
Forward
0 new messages