【问题标题】:MongoDB: &and with $matchMongoDB:和 $match
【发布时间】:2016-04-20 12:14:10
【问题描述】:

嗨:我正在使用多个 $match 和 $and 运算符,我遇到了错误:

uncaught exception: aggregate failed: {
    "errmsg" : "exception: Unrecognized pipeline stage name: '$and'",
    "code" : 16436,
    "ok" : 0
}

我的 db.version 返回 3.0.4。根据 MongoDb 文档,这应该在 3.0.x 版本中得到支持。我在这里做错了什么吗?感谢您的帮助。

这是我的查询:

db.getCollection('plannedVoyageStops').aggregate(    
    {$and : {$match:{ "scenarioId":"xxxx"},$match:{"action":"remove"}} },  
    {$unwind : "$plannedCMSs" },
    {$project: {_id: 0, scenarioId: 1, 
                "shipmentNumber":"$plannedCMSs.shipmentNumber",
                "vsId": 1, "stopSeqNum":1, "trade":1,
                "svvd": 1,                
                "action":"$plannedCMSs.action"
                }
    }
);

单匹配条件工作得很好,结果集合包含所有类型的操作,我打算只获取那些具有 action=="remove" 的操作,理想情况下。

# db.getCollection('plannedVoyageStops').aggregate(
#     {$match:{ "scenarioId":"xxxx"}},
#     {$unwind : "$plannedCMSs" },
#     {$project: {_id: 0, scenarioId: 1,
#                 "shipmentNumber":"$plannedCMSs.shipmentNumber",
#                 "vsId": 1, "stopSeqNum":1, "trade":1,
#                 "svvd": 1,
#                 "action":"$plannedCMSs.action"
#                 }
#     }
# );

【问题讨论】:

    标签: mongodb match multiple-conditions


    【解决方案1】:

    您的问题是您有两次 $match 键。这是不允许的。如果要匹配 $and 运算符中的两个条件,则需要一个条件数组。但是,这里不需要$and:在 mongo 查询中,$and 仅使用逗号隐含。只需将 JSON 查询分配给 your$match:试试

    db.getCollection('plannedVoyageStops').aggregate(    
        {$match : { "scenarioId":"xxxx","action":"remove"}},  
        {$unwind : "$plannedCMSs" },
        {$project: {_id: 0, scenarioId: 1, 
                    "shipmentNumber":"$plannedCMSs.shipmentNumber",
                    "vsId": 1, "stopSeqNum":1, "trade":1,
                    "svvd": 1,                
                    "action":"$plannedCMSs.action"
                    }
        }
    );
    

    【讨论】:

      猜你喜欢
      • 2015-06-26
      • 2018-04-28
      • 1970-01-01
      • 1970-01-01
      • 2017-08-21
      • 2013-03-10
      • 1970-01-01
      • 2015-12-03
      • 1970-01-01
      相关资源
      最近更新 更多