0

I have set up some test data in mongoDB that has the following form:

{ 
    "_id" : ObjectId("579ab44c0f9f0dc3aeec42ab"), 
    "name" : "Bob", 
    "references" : [ 1, 2, 3, 4, 5, 6 ]
}

{ 
    "_id" : ObjectId("579ab7a20f9f0dc3aeec42ac"), 
    "name" : "Jeff", 
    "references" : [ 11, 12, 13, 14, 15 ]
}

I want to be able to return the references array only for Bob. Currently I am able to return the complete Document for Bob with the following query:

  db.test_2.find({"name" : "Bob"}, bob).pretty()

Basically the general question is how to return an array for a single document in a collection in MongoDB? If I could get any help for this that would be much appreciated!

styvane
  • 59,869
  • 19
  • 150
  • 156
sachkj
  • 1
  • 1
  • Possible duplicate of [How to select a single field in MongoDB?](http://stackoverflow.com/questions/25589113/how-to-select-a-single-field-in-mongodb) – styvane Jul 29 '16 at 19:27

3 Answers3

2

You can add a projection document to limit the fields returned.

For example: db.products.find( { qty: { $gt: 25 } }, { item: 1, qty: 1 } )

Take a look at the documentation: https://docs.mongodb.com/manual/reference/method/db.collection.find/#db.collection.find

The other option would be to select the field from the given document (if you use it in a loop for example).

In any case mongo will return a json document which you need to take the array from.

Regards Jony

cohenjo
  • 576
  • 3
  • 5
  • Thanks Jony! Sorry I probably didn't explain it well enough in my original question. Your solution would just give me one array of references. I specifically want Bob's references. In other words given a name of an individual, return that individual's references. I looked at previous posts and they seemed to imply that I would need an "and" operator somewhere, but that didn't make too much sense to me. – sachkj Jul 29 '16 at 20:50
  • `db.test_2.find({ name: "Bob" }, { references: 1 });` does not work ? – Odonno Jul 29 '16 at 22:41
  • @SachinJain the reference array returned is the one found in the query - namely Bob's references. – cohenjo Jul 30 '16 at 05:19
0

You can do this...

db.test_2.findOne({ "name": "Bob" }).select({ references: 1, _id: 1 })

P.S this is with MongoDB v4.2

JS0N
  • 1
-1

db.test_2.find({ "name": "Bob" }, { "references": 1 });

thangavel .R
  • 466
  • 4
  • 13