【问题标题】:How to get all fields of a MongoDB document如何获取 MongoDB 文档的所有字段
【发布时间】:2022-08-24 01:03:06
【问题描述】:

在应用程序中,我用不同的用户在用户文档的集合中写下来。每个文档都是一个对象,其中有一个用户名和他的类别。类别是一个对象。如何获取所有记录的类别。我尝试通过 find() 来处理它们,但是我需要指定键值。我只需要指定类别字段并在那里取所有键值。如何获取单个用户的所有类别? 我需要通过钥匙找到它们。

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();
    });
});
  • 好吧,我没有很好地回答你的问题。但是请阅读有关 mongo 聚合管道的信息。这应该有助于查找嵌套文档并以链式方式执行其他操作,例如首先按名称查找并将所有类别分组,然后按类别名称排序。
  • 我需要在控制台中显示特定用户的所有类别。类别 - 这是类别和价格所在的对象。我需要将特定用户的整个对象输出到控制台。在我的示例中,我显示了名为 Bob 的用户的所有字段。我只需要显示类别
  • 试试这个:.find({user: \"Bob\"}, {categories: 1, _id: 0})
  • 不幸的是,这不起作用

标签: javascript node.js mongodb


【解决方案1】:

样本数据集

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

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

试试这个聚合管道:

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

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

两者的输出:

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

【讨论】:

    猜你喜欢
    • 2019-09-18
    • 2017-09-14
    • 2014-11-12
    • 1970-01-01
    • 2011-10-23
    • 2021-10-09
    • 1970-01-01
    • 1970-01-01
    • 2012-03-04
    相关资源
    最近更新 更多