Maciej Wawrzyńczuk
Maciej Wawrzyńczuk

Reputation: 876

MongoDB - accessing cursor with spaces in keys

I'v collection with keys containing spaces and I'v no idea how to access it from js script . For example:

c = db.collection.find()
    while(c.hasNext()) {
    print(c.next().'my key with spaces');
}

Doesn't work. How to do it?

Upvotes: 3

Views: 1032

Answers (1)

Sede
Sede

Reputation: 61225

You need to use the bracket notation [] if you keys are not a valid identifier (e.g contains spaces) instead of dot . notations to access your objects properties or documents fields. But generally speaking you should avoid using such identifier.

c = db.collection.find()
    while(c.hasNext()) {
    print(c.next()['my key with spaces']);
}

Also you can use the .forEach method instead of a while loop

db.collection.find().forEach(function(document) {
    print(document['my key with spaces']);
}

Or even better using an arrow function expression new in ECMAScript 6

db.collection.find().forEach(document => print(document['my key with spaces']))

Upvotes: 8

Related Questions