【问题标题】:MongoDB/JS: How to get all unique string values of array fieldMongoDB/JS:如何获取数组字段的所有唯一字符串值
【发布时间】:2018-01-18 07:53:30
【问题描述】:

我需要从 mongoDB 获取每个选定文档的数组的所有唯一值(使用meteorJS,这必须在服务器端完成)。

数据结构

{ 
  _id: 'Wt7gSvxSPbRw46KHK',
  parent: 'doxCi4MSNmFJE43EH',
  target: [ 'ejiSooMx6czQxzWmW', 'Q297RZEYKJdWWRyTJ' ] 
}

这是我的查询,target 是一个包含字符串元素的数组。

查询

Collection.find(
  { parent: parent, target: { $exists: true } },
  { field: { target: 1 } }
).map(doc => { return doc.target })

现在我的查询结果如下所示:

[ 
  [ 'Q297RZEYKJdWWRyTJ' ],
  [ 'Q297RZEYKJdWWRyTJ', 'ejiSooMx6czQxzWmW' ],
  [ 'ejiSooMx6czQxzWmW', 'Q297RZEYKJdWWRyTJ' ],
  [ 'ejiSooMx6czQxzWmW' ] 
]

对我来说第一个问题是映射数组的内容而不是数组本身,应该是这样的:

[ 
  'Q297RZEYKJdWWRyTJ',
  'Q297RZEYKJdWWRyTJ', 'ejiSooMx6czQxzWmW',
  'ejiSooMx6czQxzWmW', 'Q297RZEYKJdWWRyTJ',
  'ejiSooMx6czQxzWmW' 
]

至少结果应该有唯一的值:

[ 'Q297RZEYKJdWWRyTJ', 'ejiSooMx6czQxzWmW' ]

【问题讨论】:

  • 您可以添加一个示例文档吗?从那个收藏?回答您的问题将非常有帮助。
  • 在帖子中添加了数据结构

标签: javascript arrays mongodb meteor


【解决方案1】:

你可以使用.concat().apply().reduce()

var uniqArray = [].concat.apply([],
  Collection.find(
    { parent: parent, target: { $exists: true } },
    { field: { target: 1 } }
  ).map(doc => doc.target )
).reduce((acc,curr) => (acc.indexOf(curr) === -1) ? acc.concat(curr) : acc,[])

返回这个:

[
    "Q297RZEYKJdWWRyTJ",
    "ejiSooMx6czQxzWmW"
]

这是你想要的。

或者,您应该能够使用.rawCollection().distinct()

var uniqArray = Collection.rawCollection().distinct("target",{
  parent: parent, target: { "$exists": true }
})

【讨论】:

  • @user3142695 它对我有用。基本上,如果我只是用当前输出中的“数组数组”替换 Collection.find() 语句,那么所需的输出正是我得到的。
【解决方案2】:

您可以使用过滤器来获取唯一的数组元素

var unique = array.filter(function(value, index, self) { 
    return self.indexOf(value) === index;
});

【讨论】:

    【解决方案3】:

    你可以使用underscore.js干净的解决这个问题,并且它已经包含在meteor

    _.chain( Collection.find({ parent: parent, target: { $exists: true } }).fetch() )
     .pluck('target')
     .flatten()
     .value();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-05-16
      • 2017-06-06
      • 1970-01-01
      • 1970-01-01
      • 2013-04-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多