MongoDB - select 来自集合的不同值,其中值以逗号分隔

MongoDB - select distinct values from a collection where values are separated by comma

要从数据库和名为 'names' 的集合中获取不同值的列表,就像这样做一样简单:

db.name.distinct('names')

但是,我继承了 MongoDB,其中 names 包含以逗号分隔的值。 所以做 db.name.distinct('names') returns JSON 包含这样的值:

names
--------
[
"name1,name2",
"name2,name3",
"name4,name1,name3"
]

我需要从 'names' 中获取不同值的列表,所以它看起来像这样:

names
--------
[
"name1",
"name2",
"name3",
"name"
]

我需要以编程方式处理吗?

你可以试试,

  • $reduce 将数组命名为输入,$split 值与 , 它将成为 return 数组,$setUnion 将加入数组并得到 union/unique 集合中的数组,
db.collection.aggregate([
  {
    $project: {
      names: {
        $reduce: {
          input: "$names",
          initialValue: [],
          in: {
            $setUnion: [{ $split: ["$$this", ","] }, "$$value"]
          }
        }
      }
    }
  }
])

Playground


如果您想要所有记录中的唯一名称,请尝试,

  • $project 略过,同上查询
  • $unwind 解构名称数组
  • $group by null 并使用 $addToSet
  • 从名称中获取唯一值
  // skipped $project from above query

  { $unwind: "$names" },
  {
    $group: {
      _id: null,
      names: { $addToSet: "$names" }
    }
  }

Playground