Getting entire data of a mongodb collection is very simple. For example the following documents are in our Users collection

  {
  "_id":ObjectId("5ebadc45a99bde77b2efc16a"),
  "username":"tradecoder",
  "userType":"admin",
  "email":"tradecoderbd@gmail.com",
  "firstName":"trade",
  "lastName":"coder",
  "password":"12345678",
  "createdAt":"2020-12-13T16:39:30.385Z",
  "updatedAt":"2020-12-13T16:39:30.385Z"
  },
  {
  "_id":ObjectId("5ebadc45a99bde77b2efc16b"),
  "username":"user2",
  "userType":"editor",
  "email":"user2@example.com",
  "firstName":"first name",
  "lastName":"last name",
  "password":"12345678",
  "createdAt":"2020-12-14T16:39:30.385Z",
  "updatedAt":"2020-12-14T16:39:30.385Z"
  },
  {
  "_id":ObjectId("5ebadc45a99bde77b2efc16c"),
  "username":"user3",
  "userType":"author",
  "email":"user3@example.com",
  "firstName":"first name",
  "lastName":"last name",
  "password":"12345678",
  "createdAt":"2020-12-15T16:39:30.385Z",
  "updatedAt":"2020-12-15T16:39:30.385Z"
  }

We already know that we can get a required document by its _id or by any other fields, but what if we have lots of documents and need all the data at a time and if we don't know the _id numbers of all the documents? It's not complicated, practically it's super simple to get all the data from a collection. We can get it using db.collection.find(). Here is the code

Users.find({})

and the output is an array containing all the documents of that collection

[
  {
  "_id":ObjectId("5ebadc45a99bde77b2efc16a"),
  "username":"tradecoder",
  "userType":"admin",
  "email":"tradecoderbd@gmail.com",
  "firstName":"trade",
  "lastName":"coder",
  "password":"12345678",
  "createdAt":"2020-12-13T16:39:30.385Z",
  "updatedAt":"2020-12-13T16:39:30.385Z"
  },
  {
  "_id":ObjectId("5ebadc45a99bde77b2efc16b"),
  "username":"user2",
  "userType":"editor",
  "email":"user2@example.com",
  "firstName":"first name",
  "lastName":"last name",
  "password":"12345678",
  "createdAt":"2020-12-14T16:39:30.385Z",
  "updatedAt":"2020-12-14T16:39:30.385Z"
  },
  {
  "_id":ObjectId("5ebadc45a99bde77b2efc16c"),
  "username":"user3",
  "userType":"author",
  "email":"user3@example.com",
  "firstName":"first name",
  "lastName":"last name",
  "password":"12345678",
  "createdAt":"2020-12-15T16:39:30.385Z",
  "updatedAt":"2020-12-15T16:39:30.385Z"
  }
]

Working code with node, express, mongodb app

Users.find({})
.then(data=>res.send(data))
.catch(err=>res.send(err))

You also may like How to get only required data fields from MongoDB

Read more on TradeCoder : MongoDB Section


If you find this document helpful, please feel free to share it on your networks...