user555
user555

Reputation: 1529

Get unique array values records with one value exist

I have messenging platform in my app and I'm saving each message in the following format

{
   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()
}

Is there any way to get unique conversations from the collection?

for example from above list I want to get

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


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

these two records,

What can be the mongo query here?

Is there any other way than querying all the records and do unique manually?

or anyone suggests better schema, I just started with this feature so I'm in a position to change schema.

I consider using like

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

but decided against it because whenever there is new msg added to msgs array the whole field will be sent to client so using the first schema.

Any suggestions appreaciated. Thanks.

Upvotes: 0

Views: 28

Answers (2)

Derlin
Derlin

Reputation: 9881

I suggest you simply use an aggregation. For example:

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

Will return

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

You will find more details in the docs Aggregation-Distinct.

Upvotes: 0

user2326210
user2326210

Reputation:

you can use aggregation to do that,

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

Refer this to more details

And you can use $project option for make the return doc as the format you wish.

Upvotes: 1

Related Questions