首页 > 解决方案 > 聚合意外令牌:

问题描述

下面聚合 mongodb 查询给出

意外的令牌:错误

db.getCollection("products_data").aggregate(
    {
        "$unwind": {
            "path": "$color",
            "preserveNullAndEmptyArrays": true
        }
    },
    {
       "$match":{
        "country":"UK",
        "$or":[{
            "$and":[
                "$or":
                    [{
                        "$and":[
                            {"status":"drafted"},
                            {"color":{$in:["blue"]}}
                        ]},
                        {"$and":[
                            {"status1":"complete"},
                            {"status2":{$nin:["n/a","drafted","complete"]}},
                            {"color":{$in:["green"]}}

                    ]}
                ]
            ]
            },{
            "$and":[
                "$or":
                    [
                       { "$and":[
                            {"status":"drafted"},
                            {"color":{$in:["blue"]}}
                        ]},
                        {"$and":[
                            {"status1":"complete"},
                            {"status2":{$nin:["n/a","drafted","complete"]}},
                            {"color":{$in:["green"]}}

                    ]}
                ]
            ]
            }
        ]
       }

    },


    {
    "$group":{
        "_id":"$field",
        "products":{$sum: 1},
        "bid":{"$push":"$product_id"}
    }
},
{
    "$project":{
        "field":"$_id",
        "products":"$products",
        "bid":1,
        "_id":0
    }
}
);

获取给定指定条件的聚合计数。

标签: mongodbmongodb-queryaggregation-framework

解决方案


正确使用的语法aggregate和它的阶段pipeline

db.getCollection("products_data").aggregate([
  { "$unwind": { "path": "$color", "preserveNullAndEmptyArrays": true }},
  { "$match": {
    "country": "UK",
    "$or": [
      {
        "$and": [
          {
            "$or": [
              { "$and": [{ "status": "drafted" }, { "color": { "$in": ["blue"] }}] },
              { "$and": [{ "status1": "complete" }, { "status2": { "$nin": ["n/a", "drafted", "complete"] }}, { "color": { "$in": ["green"] }}]}
            ]
          }
        ]
      },
      {
        "$and": [
          {
            "$or": [
              { "$and": [{ "status": "drafted" }, { "color": { "$in": ["blue"] }}] },
              { "$and": [{ "status1": "complete" }, { "status2": { "$nin": ["n/a", "drafted", "complete"] }}, { "color": { "$in": ["green"] }}] }
            ]
          }
        ]
      }
    ]
  }},
  { "$group": {
    "_id": "$field",
    "products": { "$sum": 1 },
    "bid": { "$push": "$product_id" }
  }},
  { "$project": { "field": "$_id", "products": "$products", "bid": 1, "_id": 0 }}
])

推荐阅读