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!

1

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

3 Comments

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.
db.test_2.find({ name: "Bob" }, { references: 1 }); does not work ?
@SachinJain the reference array returned is the one found in the query - namely Bob's references.
0

You can do this...

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

P.S this is with MongoDB v4.2

1 Comment

you can set id to zero like this "_id: 0". to exclude the id
-1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.