S
S
Stanislav2017-08-10 09:48:12
MongoDB
Stanislav, 2017-08-10 09:48:12

How to get one document owned by each user?

There are two collections db.users and db.groups, when selecting, you need to get one user document (db.users)
For example, db.groups contains the following data

{
  _id: id1,
  idUser: 'ObjectID db.users._id' // String (сюда помещаю ID пользователя)
  name: 'Название группы',
  createdAt: 'Дата создания группы'
}

There is an array with user IDs [id1, id2, id3, id4]
Each user can have 100+ groups, but I need to get only 1, i.e. the output is an array of one group for each user. And you need to select the oldest group by the createdAt field.
As I understand it, aggregate will help me, but I still can’t figure it out
Groups
    .aggregate([
            {
                $project: {
                    _id: 1,
                    name: 1,
                    createdAt: 1 // Дата создания группы
                }
            }, {
                $match: {
                    idUser: {
                        $in: ['id1', 'id2', 'id3', 'id4'] // Получу все группу принадлежащие пользователям
                    }
                }
            }, {
                $sort: {
                    createdAt: 1
                }
            },{
                $group: {
                    _id: null,
                    documents: {
                        $push: {
                            name: '$name'
                        }
                    }
                }
            }
        ])........

How to correctly assemble $group so that the documents field contains groups with a unique idUser, i.e. for 5 users, you need to get 5 groups, not 500+ of the possible

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Stanislav, 2017-08-10
@ms-dred

Rest helps =)

$group: {
                    _id: "$idUser",
                    documents: {
                        $first: {
                            _id: "_id",
                            name: '$name',
                            idUser: "$idUser"
                        }
                    }
                }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question