如何在mongoose中克隆聚合对象副本

pbpqsu0x  于 2023-06-23  发布在  Go
关注(0)|答案(1)|浏览(83)

我想克隆聚合对象的副本以执行2种类型的查询。我的示例代码如下

const aggregation = db.users.aggregate().match(query);

// From there I want to split this into 2 clone object.
// Suppose there was a .clone function
const aggregation1 = aggregation.clone().count('total');
const aggregation2 = aggregation.clone().skip(skip).limit(limit);

Promise.all([aggregation1.exec(), aggregation2.exec()]);

我如何才能做到这一点?我很感激任何帮助,提前感谢。

rks48beu

rks48beu1#

我想克隆聚合到另一个对象,所以我做了如下

userCollection = User.aggregate();
userCollection.match({ _id: { $ne: new ObjectId("anyid")} });
//cloning to another object
let checkCount =  User.aggregate(userCollection);
let rsdata = await checkCount.count("total").exec();
//Now rsdata having total count but still you can use userCollection 
//total will be not added to userCollection pipeline
rs = userCollection.exec((err, documents) => {
      if(err){
          console.log(err);
          return false;   
      }
      console.log(documents);
      return true;
}

那我得先清点记录,然后才能拿到记录。
在上面的代码中,我已经克隆了userCollection到checkCount对象。因此,如果在checkCount上添加任何附加阶段,它不会影响userCollection。
我希望这会有所帮助。
Happy Coding:)

相关问题