Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Return only one field from MongoDB query

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

How can I retrieve only that array?

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading