如何在 Node.js 中聚合 MongoDB

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23805772/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 17:22:16  来源:igfitidea点击:

How to MongoDB aggregation in Node.js

node.jsmongodbmongoose

提问by user3664775

var mongoose = require('mongoose');
var membersModel = require('./model_member.js');
exports.request_friend_list = function(req, res){
var userid=req.body.userid;
console.log(userid);

//  membersModel.find({_id: userid,friends:{status:0}},{_id:0,'friends':1,},function(err,data)
    membersModel.aggregate(
         {$match: {_id:userid}},
         {$project: {friends: 1}},
         {$unwind: "$friends"},
         {$match: {"friends.status": 0}}
     ,function(err,data){
     if(err){
        res.json({status:"error"});
        throw err;
    }else{
        if(JSON.stringify(data).length > 0){
            console.log(JSON.stringify(data));
            res.json(data);
        }
        else{
            res.json({status: "Data is not Exist."});
            console.log("Data is not Exist.");
        }
    }   
});

membersModel.find({...})is operating normally, but memberModel.Aggregation({...})is not working. This also works in MongoDB:

membersModel.find({...})运行正常,但memberModel.Aggregation({...})不工作。这也适用于 MongoDB:

db.members.aggregate({$match:_id: ObjectId("532b4729592f81596d000001"),$project:"friends":1,$unwind:"$friends",$match:"friends.status": 0})

What is the problem?

问题是什么?

回答by Neil Lunn

The likely problem here is that your useridvalue is not actually a correct ObjectIDtype when it is being passed into the pipeline. This results in nothing being "matched" in the initial stage.

这里可能的问题是,当您的useridObjectID被传递到管道时,它实际上并不是正确的类型。这导致在初始阶段没有任何“匹配”。

Therefore as a more complete example:

因此,作为一个更完整的例子:

var mongoose = require("mongoose");
var Schema = mongoose.Schema;
var ObjectID = require("mongodb").ObjectID;

mongoose.connect("mongodb://localhost/test");

friendSchema = new Schema({
  "name": String,
  "status": Number
});

memberSchema = new Schema({
  friends: [friendSchema]
});

var Member = mongoose.model("Members", memberSchema );

var userid = new ObjectID("537ec520e98bcb378e811d54");

console.log( userid );

Member.aggregate([
  { "$match": { "_id": userid } },
  { "$unwind": "$friends" },
  { "$match": { "friends.status": 0 } }],
  function( err, data ) {

    if ( err )
      throw err;

    console.log( JSON.stringify( data, undefined, 2 ) );

  }
);

Which then will match data as expected:

然后将按预期匹配数据:

[
  {
    "_id": "537ec520e98bcb378e811d54",
    "friends": [{
      "name": "Ted",
      "status": 0
    }]
  }
]

So be careful to make sure this is of the correct type. The aggregate method does not automatically wrap a string value such as "537ec520e98bcb378e811d54" into an ObjectIDtype when it is mentioned in a pipeline stage against _idin the way that Mongoose does this with other find and update methods.

所以要小心确保这是正确的类型。ObjectID当在管道阶段提及时,聚合方法不会自动将字符串值(例如“537ec520e98bcb378e811d54”)包装成一种类型_id,而 Mongoose 使用其他查找和更新方法执行此操作的方式。