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
You can specify a projection, in your find function:
First, you are returning your data as
results
, and try toconsole.log(result)
, which is different variable name.If you want to take only
сategories
for each user in database andconsole.log()
them, you can do it like this: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 inresults
array, and map it to itscategories
property.