0

i try to get one element form array from Mongodb collection. I no need array with all data, i just need one element of it. So my db is like this:

_id: ObjectId("...")
arrayName :Array
    : 'string1'
    : 'string2'
    ...

Is there an option to get only one element of an array? for example the first one. This is my function, but this return all element of the array.

db.collection('collectionName')
  .find()
  .toArray()
  .then((result) => {
    response.data = result;
    res.json(response);
  })

I tried to use function findOne() instead of find(), but it does't work the way I want. thanks for help.

Akida
  • 5
  • 2
  • 1
    Possible duplicate of [Retrieve only the queried element in an object array in MongoDB collection](https://stackoverflow.com/questions/3985214/retrieve-only-the-queried-element-in-an-object-array-in-mongodb-collection) – Ashh Sep 14 '18 at 07:54
  • Please provide your mongoDB data with proper formate – IftekharDani Sep 14 '18 at 11:02

1 Answers1

0

Use it like this

db.collection('collectionName').findOne({},function(err,doc){
    //here doc value will return you json so you can push it in array
    let recordarray = []; 
    recordarray.push(doc);
});
c-chavez
  • 7,237
  • 5
  • 35
  • 49
Anku Singh
  • 914
  • 6
  • 12