userName
userName

Reputation: 955

How to get all elements in document object MongoDB

I have objects with users in my collection. Each document is a separate user that stores the username and category. Categories is an object that contains categories and costs. I need to get all categories in one user. How can i do this? find({ name: "Bob"}) finds all fields in the given document. And I need to take an object with categories and output the contents of category: {...} to the console. How can i do this?

let users = [
  {
    name: "Bob",
    сategories: {
      eat: "20$",
      entertainment: "100$",
    },
  },
];

mongoClient.connect(function(err, client) {
  if (err) return console.log(err);

  const db = client.db("expensesdb");
  db.collection("users").find({
    name: "Bob"
  }.toArray(function(err, results) {
    console.log(result);
    client.close();
  });
});

Upvotes: 0

Views: 638

Answers (2)

NeNaD
NeNaD

Reputation: 20354

First, you are returning your data as results, and try to console.log(result), which is different variable name.

If you want to take only сategories for each user in database and console.log() them, you can do it like this:

db.collection("users").find(
  { name: "Bob" },
  { сategories: 1 }
).toArray(function(err, results) {
  console.log(results.map(user => user.сategories));
  client.close();
});

Note: results will be an array of users because there can be multiple documents returned for specified query. map() is used to iterate over each item in results array, and map it to its categories property.

Upvotes: 1

Charchit Kapoor
Charchit Kapoor

Reputation: 9284

You can specify a projection, in your find function:

mongoClient.connect(function(err, client) {
  if (err) return console.log(err);

  const db = client.db("expensesdb");
  db.collection("users").find({
    name: "Bob"
  },{projection: {name: 0, _id: 0}}).toArray(function(err, results) { 
    console.log(results);
    client.close();
  });
});

Upvotes: 1

Related Questions