如何在没有键的情况下仅在Mongo DB中获取特定字段?

时间:2016-01-13 11:06:21

标签: node.js mongodb mongoose

我的数据集如下:

{ "_id" : "EVNQUERY-k9Uoo74Q3WcdmU", "event_data" : "{\"data\":\"helo\"}", "event_name" : "onOemPushAlert", "timestamp_start" : 1452678481433, "timestamp_end" : 1452678481433, "sender" : "USR-ADMIN", "status" : "pending", "query" : { "user" : { "and" : [ { "email" : { "eq" : "" } } ] } }, "updated_on" : ISODate("2016-01-13T09:48:01.459Z"), "created_on" : ISODate("2016-01-13T09:48:01.459Z") }

{ "_id" : "EVNQUERY-yAKmrbzs2JeaUY", "event_data" : "{\"data\":\"ji\"}", "event_name" : "onOemPushAlert", "timestamp_start" : 1452681060159, "timestamp_end" : 1452681060159, "sender" : "USR-ADMIN", "status" : "pending", "query" : { "user" : { "@@@and@@@" : [ { "email" : { "eq" : "" } } ] } }, "updated_on" : ISODate("2016-01-13T10:31:00.223Z"), "created_on" : ISODate("2016-01-13T10:31:00.223Z") }

{ "_id" : "EVNQUERY-0NeCstt2eJchDZ", "event_data" : "{\"data\":\"hyg\"}", "event_name" : "onOemPushAlert", "timestamp_start" : 1452681073882, "timestamp_end" : 1452681073882, "sender" : "USR-ADMIN", "status" : "pending", "query" : { "user" : { "@@@and@@@" : [ { "email" : { "eq" : "" } } ] } }, "updated_on" : ISODate("2016-01-13T10:31:13.897Z"), "created_on" : ISODate("2016-01-13T10:31:13.897Z") }

我在查询后运行

db.eventqueries.find({},{_id:1})

但它给了我

{ "_id" : "EVNQUERY-k9Uoo74Q3WcdmU" }
{ "_id" : "EVNQUERY-yAKmrbzs2JeaUY" }
{ "_id" : "EVNQUERY-0NeCstt2eJchDZ" }

但我想要的是

["EVNQUERY-k9Uoo74Q3WcdmU", "EVNQUERY-yAKmrbzs2JeaUY", "EVNQUERY-0NeCstt2eJchDZ"]

2 个答案:

答案 0 :(得分:1)

针对该集合上的_id字段执行 distinct() 查询:

db.eventqueries.distinct("_id")

在node.js驱动程序中运行 distinct() 命令,该命令将对结果进行回调:

collection.distinct("_id", function(err, docs) {
    if (err) { /* handle error */ };
    console.log(docs);
});

答案 1 :(得分:0)

您可以使用聚合来实现您想要的效果。你可以尝试一下

db.eventqueries.aggregate([
   {
       $group : {
           keys : { $push : "_id" }
       }
   }
])