【问题标题】:Get unique array values records with one value exist获取具有一个值的唯一数组值记录
【发布时间】:2016-06-07 21:24:15
【问题描述】:

我的应用中有消息传递平台,我将每条消息保存为以下格式

{
   userIds: [ 'user1Id', 'user2Id' ],
   msg: "message",
   sentBy: 'user1',
   sentAt: new Date()
}


{
   userIds: [ 'user1Id', 'user3Id' ],
   msg: "message",
   sentBy: 'user1',
   sentAt: new Date()
}


{
   userIds: [ 'user1Id', 'user2Id' ],
   msg: "message",
   sentBy: 'user1',
   sentAt: new Date()
}

有什么方法可以从集合中获得独特的对话?

例如我想从上面的列表中得到

  {
       userIds: [ 'user1Id', 'user2Id' ],
       msg: "message",
       sentBy: 'user1',
       sentAt: new Date()
    }


    {
       userIds: [ 'user1Id', 'user3Id' ],
       msg: "message",
       sentBy: 'user1',
       sentAt: new Date()
    }

这两条记录,

这里的 mongo 查询可以是什么?

除了查询所有记录并手动进行唯一性之外,还有其他方法吗?

或者任何人建议更好的架构,我刚开始使用此功能,所以我可以更改架构。

我考虑使用like

{
   userIds: [ 'user1Id', 'user2Id' ],
   msgs: [
    {
       msg: "message",
       sentBy: 'user1',
       sentAt: new Date()
    },
    {
       msg: "message",
       sentBy: 'user2',
       sentAt: new Date()
    }
  ],
   modifiedAt: new Date()
}

但决定反对它,因为每当有新的 msg 添加到 msgs 数组时,整个字段都会发送到客户端,因此使用第一个模式。

任何建议appreaciated。谢谢。

【问题讨论】:

    标签: mongodb meteor


    【解决方案1】:

    您可以使用聚合来做到这一点,

    .aggregate([{$group:{_id:"$userIds"}}])

    更多详情请参考this

    您可以使用 $project 选项将返回文档设为您希望的格式。

    【讨论】:

      【解决方案2】:

      我建议您简单地使用聚合。例如:

        db.test.aggregate( {$group: {_id: "$userIds" } } )
      

      会回来

      {
          "result" : [
              {
                  "_id" : [
                      "user1Id",
                      "user3Id"
                  ]
              },
              {
                  "_id" : [
                      "user1Id",
                      "user2Id"
                  ]
              }
          ],
          "ok" : 1
      }
      

      您将在文档Aggregation-Distinct 中找到更多详细信息。

      【讨论】:

        猜你喜欢
        • 2014-06-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-02-10
        相关资源
        最近更新 更多