0
// MongoDb User Object:

const new_schema = new Schema({
    name: {
        first: {type: String},
        last: {type: String},
    },
    currentPrivateLocation: {type: [String], default: []} 
});



// Aggregation:

let pipeline = [{
    $match: query
}];

pipeline.push({
  $sort: sortObj
});

pipeline.push({
    $group: {
        _id: null,
        count: {$sum: 1},
        result: {$push: '$$ROOT'},
    }
});

pipeline.push({
    $project: {
        _id: 0,
        count: 1,
        result: {
            $slice: ['$result', Number(limit * (page - 1)), limit]
        }
    }
});

In MongoDB, I aggregate a collection to get the data in this format:

{ 
    count: 2,
    result: 
    [ 
        { _id: 57e55d55d9a7041100ac5e26,
          subjectIds: [Object],
          role: [Object]
        },
        { _id: 58e5d545g9a7041500ac4526,
          subjectIds: [Object],
          role: [Object]
        }
    ]
}

I now want to do a $lookup based on the _id of the objects inside 'result'. When I try to $unwind result, it just turns the result array into a result object with only the first element.

Any thoughts?

Louis B
  • 342
  • 1
  • 5
  • 21
  • If i understand your requirement correctly - you would want to call $unwind result._id – Rishikesh Dhokare Jan 12 '18 at 15:43
  • When I do $unwind it does not work. – Louis B Jan 12 '18 at 15:44
  • I see. This could be the possible duplicate - https://stackoverflow.com/questions/34967482/lookup-on-objectids-in-an-array – Rishikesh Dhokare Jan 12 '18 at 15:46
  • I've read that post but the issue is when I $unwind result, it only gives me the first element of the array, it does not convert the entire array. – Louis B Jan 12 '18 at 16:00
  • Can you add the entire aggregation query with some sample documents and expected output ? It looks like you may a problem in some other part of code. – s7vr Jan 12 '18 at 16:07
  • @Veeram, check the updated post – Louis B Jan 12 '18 at 16:25
  • I don't see anything obvious in query. Are you sure you are looking at the correct set of documents when verifying ? I would recommended adding the documents from your collection which can reproduce the behavior for us. Thats the only way to confirm the issue. – s7vr Jan 12 '18 at 17:22
  • These are the correct set of documents. Are you referring to the query in $match? If so, that query is irrelevant. The relevant part is the $group and $project part which alters the data format. – Louis B Jan 12 '18 at 17:52
  • I'm referring the documents that you get after $project stage. Like I said its something you can see and we cant unless you provide the data & input arguments (limit & page) for us to run the query. May be $slice doesn't work as you think it should. – s7vr Jan 12 '18 at 18:05
  • My problem is that I am trying to $unwind AFTER I $group. Is there a way to accomplish this? – Louis B Jan 26 '18 at 20:14

0 Answers0