【问题标题】:How to get distinct values from MongoDB?如何从 MongoDB 中获取不同的值?
【发布时间】:2020-05-30 04:40:52
【问题描述】:

我是 MongoDB 的新手,很难从那里获得不同的值。

这是集合中的文档,我想通过 "CustomerAccountNo" 来区分(这是重复值 = 165)

   {
        "_id": "5e3eaf3ef5aab73568bd8494",
        "CustomerAccountNo": "123",
        "Customer": "Lucy Thom"
    },
    {
        "_id": "5e3eaf40f5aab73568bd8495",
        "CustomerAccountNo": "325",
        "Customer": "Nick Granger"
    },
    {
        "_id": "5e3eaf42f5aab73568bd8496",
        "CustomerAccountNo": "658",
        "Customer": "Tommy Tee"
    },
    {
        "_id": "5e3eaf44f5aab73568bd8497",
        "CustomerAccountNo": "6513",
        "Customer": "Carlos Nolasco"
    },
    {
        "_id": "5e3eaf49f5aab73568bd8498",
        "CustomerAccountNo": "165",
        "Customer": "Hungarian Pastry shop"
    },
    {
        "_id": "5e4660e9f57ea925a42b4ba2",
        "CustomerAccountNo": "165",
        "Customer": "Hungarian Pastry shop"
    }

并希望输出如下:

    {
        "_id": "5e3eaf3ef5aab73568bd8494",
        "CustomerAccountNo": "123",
        "Customer": "Lucy Thom"
    },
    {
        "_id": "5e3eaf40f5aab73568bd8495",
        "CustomerAccountNo": "325",
        "Customer": "Nick Granger"
    },
    {
        "_id": "5e3eaf42f5aab73568bd8496",
        "CustomerAccountNo": "658",
        "Customer": "Tommy Tee"
    },
    {
        "_id": "5e3eaf44f5aab73568bd8497",
        "CustomerAccountNo": "6513",
        "Customer": "Carlos Nolasco"
    },
    {
        "_id": "5e3eaf49f5aab73568bd8498",
        "CustomerAccountNo": "165",
        "Customer": "Hungarian Pastry shop"
    }

我正在尝试下面的代码来获得上述响应,

collectionName.distinct("CustomerAccountNo") 

collectionName.aggregate([
  { $group: { _id: { CustomerAccountNo: "$CustomerAccountNo", Customer: "$Customer" } } }
]);

但是上面的代码都没有按照我的意愿存档正确的响应,我不知道我做错了什么。

【问题讨论】:

标签: mongodb mongodb-query aggregation-framework


【解决方案1】:

这个聚合会得到需要的结果:

db.test.aggregate( [
  { $group: { _id: "$CustomerAccountNo", doc: { $first: "$$ROOT" } } },
  { $replaceRoot: { newRoot: "$doc" } }
] ).pretty()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-11-18
    • 2020-06-29
    • 1970-01-01
    • 2012-08-19
    • 1970-01-01
    • 2015-07-24
    • 1970-01-01
    相关资源
    最近更新 更多