S
S
Stanislav2020-01-23 20:58:12
MongoDB
Stanislav, 2020-01-23 20:58:12

How to merge collections and get only the first entry in the array?

Is it possible to implement everything like this?
There are two collections
First: Collections

var schema = new Schema({
    name: { type: String },
    owner: { type: mongoose.Schema.Types.ObjectId, ref: 'Users' }, // владелец
    photos: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Photos' }],
    public: { type: Number, default: 1 },
    createdAt: { type: Date, default: Date.now }
})

Second: Photos
var schema = new Schema({
  createdAt: 			{ type: Date,		default: Date.now },
  owner: 				{ type: mongoose.Schema.Types.ObjectId, ref: 'Users', required: !0 },
        image: 				{ type: String, 	required: !0 },
  domain: 			        { type: String, 	default: config.domain.photos },
});

What is there, what is there owner Users._id
I need to get all user data from Collections, for this I do the following:
Collections.aggregate([
        { $match: { owner: request.owner } },
        { $sort: { createdAt: -1 } },
        { $lookup: { from: 'photos', localField: 'photos', foreignField: '_id', as: 'photos' } },
        {
            $project: {
                _id: { $toString: "$_id" },
                name: 1,
                photos: {
                    "$map": { 
                        input: "$photos",
                        as: "p",
                        in: { $concat: ['$$p.domain', 'folder/', '$$p.image'] } }
                }
            }
        }
    ])

And at the output I get the correct object
{
    name: 'Папка',
    _id: '5d557777ab6666e77777e',
    photos: [
      'https://site/folder/img.jpg',
      'https://site/folder/img2.jpg''
    ]
  }

But the photos field contains a bunch of entries, and I only need one to be like this
{
    name: 'Папка',
    _id: '5d557777ab6666e77777e',
    photos: 'https://site/folder/img.jpg',
  }

Or for photos to be an array with one element.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Stanislav, 2020-01-23
@ms-dred

I got there myself

photos: {
 $arrayElemAt: [{
  "$map": { 
   input: "$photos",
   as: "p",
   in: { $concat: ['$$p.domain', 'folder/', '$$p.image'] } }
  }, 0 ]
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question