3

Suppose my document looks like this

{
    "_id": 2,
    "Name": "Abcd",
    "Connected": [1,3]
}

Now, I want to retrieve the array [1,3] via the _id or Name. The purpose is to save this array into a JavaScript array.

Hence I tried using db.myCollection.find({"_id":2},{"Connected":1}) but it return a document again moreover with _id still there like this

{ "_id" : 2, "Connected" : [ 1, 3 ] }

How can I retrieve only that array?

Luca Kiebel
  • 9,790
  • 7
  • 29
  • 44
mr.loop
  • 818
  • 6
  • 20
  • 1
    You get the document back, just use `document.Connected` to get the array... – Luca Kiebel Jan 10 '22 at 09:07
  • @LucaKiebel `db.myCollection.find({"_id":2},{"Connected":1}).Connected` is this what you meant. But I don't get any result. – mr.loop Jan 10 '22 at 09:13
  • Is that find method synchronous? What mongo library are you using? – Luca Kiebel Jan 10 '22 at 09:15
  • 1
    @LucaKiebel I am not using any mongo library. I am putting the queries into a javascript file and then running mongo shell via `mongo myDb < jsFile.js` – mr.loop Jan 10 '22 at 09:16
  • 1
    I see that you need to exclude the `_id` field explicitly, in the projection. Also, note that, the `find` method return a _cursor_. Cursor has methods to extract the required data. Optionally, `findOne` returns single document. To retrieve the array field only, on the extracted document and use the `.Connected` on it. – prasad_ Jan 10 '22 at 09:24
  • 1
    @prasad_ thanks. doing `arr = db.coll.find(...).toArray()` and then `arr[0].Connected` return the required result. – mr.loop Jan 10 '22 at 09:31

1 Answers1

5

You can optionally remove the ID from your result, by setting it to 0 in the projection:

db.myCollection.find({"_id":2},{"Connected":1, "_id":0})

The ID field is the only field that can be excluded in projections while other fields are included.

If you want to get the Connected field directly, you can use findOne:

db.myCollection.findOne({"_id":2}, {"Connected":1, "_id":0}).Connected
Luca Kiebel
  • 9,790
  • 7
  • 29
  • 44
  • 1
    Thanks. Although your assumption of doing `.Connected` on the returned Document was correct, it probably doesn't work on the cursor directly. Doing `toArray()` first is what was needed. – mr.loop Jan 10 '22 at 09:37
  • 2
    The second query works but only in the `mongosh` shell and not in `mongo`. In `mongo`, one still has to first do `arr = db.coll.find(...).toArray()` and then `arr[0].Connected` – mr.loop Jan 10 '22 at 09:52