在MongoDB中获取字段所有值的最有效方法& Node.js的

时间:2013-11-21 14:14:38

标签: node.js mongodb

所以我对MongoDB和文档存储内容都很陌生。我正在努力寻找最优雅,最有效的解决方案,以便做到以下几点:

我有一个叫做测试的集合。在每个测试中,都有一个字段所有者的操作。见下文:

{
"_id" : ObjectId("528c731a810761651c00000f"),
"actions" : [
    {
        "action" : "6784",
        "owner" : "MERCHAND_1",
        "_id" : ObjectId("528c7292810761651c00000e")
    },
    {
        "action" : "1",
        "owner" : "MERCHAND_1",
        "_id" : ObjectId("528c7292810761651c00000d")
    },
    {
        "action" : "1358",
        "owner" : "MERCHAND_2",
        "_id" : ObjectId("528c7292810761651c00000c")
    }
],
"name" : "Test 1",
"product" : ObjectId("528bc4b3a0f5430812000010")

}

如何使用Node.js& amp;来获取每个不同所有者值的列表(数组)。 MongoDB(我使用的是mongoose驱动程序)。在mongoside或node.js方面做得更好吗?例如,如果我在上一个表上运行该函数,它应返回:

[
    {
      "owner":"MERCHAND_1"
    },
    {
      "owner":"MERCHAND_2"
    }
]

2 个答案:

答案 0 :(得分:11)

MongoDB支持distinct命令来执行此操作。您可以使用点表示法来定位数组中的字段,如本例所示。在shell中:

db.test.distinct('actions.owner')

输出:

[
  "MERCHAND_1",
  "MERCHAND_2"
]

答案 1 :(得分:7)

您可以使用命令

对MongoDB执行此操作
db.runCommand({
  distinct: 'tests',
  key: 'actions.owner'
});

给你

{
  "values" : [
    "MERCHAND_1",
    "MERCHAND_2"
  ],
  "stats" : {...},
  "ok" : 1
}

这将包括tests集合中的每个文档。但是,如果您只想检查单个文档,则可以将命令重新编写为

db.runCommand({
  distinct: 'tests',
  key: 'actions.owner',
  query: { _id: ObjectId("528c731a810761651c00000f") }
});
相关问题