1

I'm new to MongoDB, and I'm trying to get results in a different way.

if I execute the query db.collection.find().toArray() I get something like:

[
  {
    "_id":"34234...",
    "first":"Mark",
    "last":"Marker"
  },
  {
    "_id": "34235...",
    "first":"Adam",
    "last":"Smith"
  }
]

is there an api that lets you to receive the results as the following?:

{
 "results" : {

  "34234..." :{
    "_id":"34234...",
    "first":"Mark",
    "last":"Marker"
  },
  "4235..." :{
    "_id": "34235...",
    "first":"Adam",
    "last":"Smith"
  }

 }

Or I need to get the results array and iterate every single object and build my response? (I would like to avoid the single cursor iteration)

1 Answer 1

0

I don't believe there's a native API function for that. cursor.toArray() goes through each item in the cursor begin with, so I wouldn't worry too much about that. We can just skip the toArray() and do our own iteration:

var obj = {}
db.collection.find().each(function(item){
  obj[item._id] = item;
});

I don't think that would really be any slower.

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

2 Comments

Ok I wanted to avoid this solution because my collections are on another server, so I suppose the "each()" function would be a request to the server( am I wrong?) If there is no API and I am not wrong about the previous thought, I think the solution is to get the results array and iterate it by (e.g.) NodeJS building my response.
I'm not sure I understand. You have to get the data off the server one way or another, right? This solution doesn't do any iteration or access that toArray wouldn't be doing anyway (it consumes the cursor just like each does). Iterating through the result of toArray() is a bit less efficient, since it has to iterate through the cursor and then iterate through the array.

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.