尝试匹配 mongodb 中的条件列

Try to match conditional column in mongodb

我是 mongodb 的新手,现在正在使用聚合。 我遇到一个问题,我有 2 列让这个 column1 和 column2 我想通过 $match 中的 column1 或 column2 匹配是否可能。我卡住了,请帮忙。

数据库结构:

{
  "_id" : ObjectId("55794aa1be1f8fe822da139d"),
  "transactionType" : "1",
   "_store" : {
    "storeLocation" : "Pitampura",
    "storeName" : "Godown",
    "_id" : "5576b5c5e414d90c03d1e330"
  }
}

我尝试根据 transactionType 和 storeName 进行过滤,我将这 2 个参数发送到 api 但是当 storeName 作为空字符串发送时,则仅根据两个参数的 transactionType else 进行过滤。不想使用 if-elseif。

当然可以满足您的查询。您只需按如下方式处理:

// Initial data
var request = { "storeName": "", "transactionType": "1" };

// Transform to array
var conditions = Object.keys(request).map(function(key) {
    var obj = {},
        newKey = "";
    if ( key == "storeName" ) {
        newKey = "_store." + key;
    } else {
        newKey = key;
    }

    obj[newKey] = request[key];
    return obj;
});

db.collection.find({ "$or": conditions });

转换后的整个结构分解为:

db.collection.find({
    "$or": [
        { "_store.storeName": "" },
        { "transactionType": "1" }
    ]
})

在满足"transactionType"的条件下当然匹配文档

这就是 $or 所做的,认为查询参数中的至少一个条件与文档中的数据相匹配。

这里的另一件事是,由于请求中显示的数据不是文档中数据的 "direct match",因此对 "key name" 进行操作以使用正确的 [=16] =] 用于访问该元素的表单。

这些只是基本查询,因此相同的规则适用于聚合 $match,聚合本身只是一个查询元素:

db.collection.aggregate([
    // Possibly other pipeline before

    // Your match phase, which probably should be first
    { "$match": {
        "$or": [
            { "_store.storeName": "" },
            { "transactionType": "1" }
        ]
    }},

    // Other aggregagtion pipeline

])