1

I'm trying to get only the value of a specific MongoDB field, and have the following code:

var collection = db.collection('people');

collection.find({"name" : "John" }, { phone : 1, _id : 0 }).toArray(function (err, result) {
    if (err) {
        console.log(err);
    } else if (result.length) {
        console.log(result);
    } else {
        socket.emit("No documents found");
    };
});

This works great however it gives me the following result:

[ { phone: 112233 } ]

How can I edit the query so that it will return only "112233", or how can I split the array "phone: 112233" so that it will give me the value only?

Any help is greatly appreciated.

P.S. I tried forEach and MongoDB aggregate, to no avail as of the moment.

Robert Moskal
  • 21,737
  • 8
  • 62
  • 86
Neekoy
  • 2,325
  • 5
  • 29
  • 48

1 Answers1

3

Split it like this:

result[0].phone
Robert Moskal
  • 21,737
  • 8
  • 62
  • 86
  • Oh wow, I made a shameful amount of tries and in the end it turns out to be so simple. Not sure who downvoted you, however this is the correct answer. Thanks a lot. :) – Neekoy Jun 10 '16 at 21:05
  • I made a snarky comment at first. I started Seriously? Don't worry about it. – Robert Moskal Jun 10 '16 at 21:10
  • Haha I noticed - it doesn't reflect the edits in the notification history. It's okay though, it was a lame question anyway (in hindsight). – Neekoy Jun 10 '16 at 21:11