skip to Main Content

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();
  });
});

2

Answers


  1. 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();
      });
    });
    
    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search