ForEach on Array Index

2,324 views
Skip to first unread message

x0ne

unread,
Mar 17, 2011, 12:53:52 AM3/17/11
to mongodb-user
I have the following data nested within a document:

{ "report" : [
"2009-10-05 11:09:40",
{
"random_dwqdqwd" : "value",
"random_djwkdjwkd" : "null",
}
]
}

In mongo I am trying to do a forEach on this specific portion of data
and somehow extract the key and value located with the [1] index of
the data. The key in this data is random/dynamic and therefore I
cannot hardcode the key when iterating through the results. I know I
have access to the data, but I don't know how to access the value if I
do not know the key.

Here is the query I have been using:

db.docs.find({},{"report":1}).forEach(
function(z) {
print("data: " + z);
}
);

When "z" outputs I get a bson object, but I am not able to get the key
or value by saying something like "z.1" or "z[1]". If I needed to get
the key name and the value, what is the best way to do so? This data
comes from another source so I would like to avoid reparsing it before
throwing it into Mongo.

Scott Hernandez

unread,
Mar 17, 2011, 1:04:49 AM3/17/11
to mongod...@googlegroups.com
z is the document/object, not an array.

I think you want z.report[0]; this is all basic javascript stuff and
has nothing to do with bson.

> var z = {a:[1,2,3]}
> z.a
[ 1, 2, 3 ]
> z.a[0]
1
> db.t1.insert(z)
> db.t1.findOne().a[0]
1

you can use a for loop to get the keys from any javascript object;
then you can get the data.

> for(key in z) print(key)
a
> for(key in z.a) print(key)
0
1
2

> comes from another source so I would like to avoid reparsing it before
> throwing it into Mongo.

I don't know what you mean here. If you are working with javascript
objects then it will need to be encoded to bson before being saved in
mongodb.

>
> --
> 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.
>
>

Reply all
Reply to author
Forward
0 new messages