简体   繁体   中英

How to get all fields of a MongoDB document

In application I write down in a collection of users documents with separate users. Each document is an object in which there is a name of the user and his category. Categories are an object. How can I take all recorded categories. I try to take them through find (), but there I need to specify the key-value. And I just need to specify the category field and take all the key-values there. How can I get all categories of an individual user? I need to find them by key.

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

Sample data-set

{ "_id" : ObjectId("63050125848392dcf6f3ebba"), "name" : "max", "category" : { "cat1" : "max1", "cat2" : "max2" } }

{ "_id" : ObjectId("63050132848392dcf6f3ebbb"), "name" : "box", "category" : { "cat1" : "box1", "cat2" : "box2" } }

Try this aggregation pipeline:

db.users.aggregate([
    { $match: { "name": "max" } },{$project : {"category":1}}
  ]);

db.users.aggregate([
    { $match: { "category.cat1": "cat1" } },{$project : {"category":1}}
  ]);

Output for both:

{ "_id" : ObjectId("630500ec848392dcf6f3ebb9"), "category" : { "cat1" : "cat1", "cat2" : "cat2" } }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM