简体   繁体   中英

Mongoose, limit each element of array result

To find objects with array of ids we can do this:

var idsArray = ['id1', 'id2', 'id3'];
 SomeObject.find({'chatroomId': { $in: idsArray}}).exec();
  .then(function(someObjects) {
    console.log(someObjects);
})

Is it possible to limit result for each member in array? Not for whole result like this:

SomeObject.find({'chatroomId': { $in: idsArray}}).limit(3)

but for each element. Maybe something like this:

SomeObject.find({'chatroomId': { $in: idsArray.forEach.limit(3)}});

Considering that you have a document structure like :

{
    _id : ObjectId("591931855d0aad80c996eab2)",
    chatName : 'SchoolChat',
    chatrootId : ['id1', 'id2','id3','id4','id5']
}

You can use following query to get what you need :

db.collection_name.aggregate([ 
    { $unwind : '$chatrootId' },
    { $limit : 3}, 
    { $group : {
        _id : '$_id',
        chatName : { $first : '$chatName' },
        chatroomId : { $push : '$chatrootId' },
        } 
    }   
]);

It will give you :

{ 
    "_id" : ObjectId("591931855d0aad80c996eab2"), 
    "chatName" : "SchoolChat", 
    "chatroomId" : [ 'id1', 'id2', 'id3'] 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM