猫鼬查询以过滤数组并填充相关内容

ugl*_*ode 6 mongoose mongodb node.js mongodb-query aggregation-framework

我试图查询该属性,该属性是对另一个架构的引用和一些其他数据的数组。为了更好的说明,以下是模式:

    var orderSchema = new Schema({
        orderDate: Date,
        articles: [{
            article: {
                type: Schema.Types.ObjectId,
                ref: 'Article'
            },
            quantity: 'Number'
        }]
    }),
    Order = mongoose.model('Order', orderSchema);
Run Code Online (Sandbox Code Playgroud)

虽然我成功地查询了引用,即:

Order.find({}).populate('articles.article', null, {
    price: {
        $lte: 500
    }
}).exec(function(err, data) {
    for (var order of data) {
        for (var article of order.articles) {
            console.log(article);
        }
    }
});
Run Code Online (Sandbox Code Playgroud)

我在查询quantity属性时遇到了一些问题,即这不起作用:

Order.find({}).where({
    'articles.quantity': {
        $gte: 5
    }
}).populate('articles.article', null, {
    /*price: {
        $lte: 500
    }*/
}).exec(function(err, data) {
    for (var order of data) {
        for (var article of order.articles) {
            console.log(article);
        }
    }
});
Run Code Online (Sandbox Code Playgroud)

甚至有可能基于查询quantity吗?如果是这样,最好的方法是什么?

谢谢!

更新:

问题是,结果要么是一个完整的数组,要么什么都不是(请参阅更新的问题)。我只想获取数量大于或等于5的那些记录。使用您的(和我的)方法,我要么根本没有任何记录(如果我设置了$ gte:5001),要么没有任何记录(如果我设置了$ gte: 5000)

{
    "_id": ObjectId('56fe76c12f7174ac5018054f'),
    "orderDate": ISODate('2016-04-01T13:25:21.055Z'),
    "articles": [
        {
            "article": ObjectId('56fe76c12f7174ac5018054b'),
            "quantity": 5000,
            "_id": ObjectId('56fe76c12f7174ac50180551')
        },
        {
            "article": ObjectId('56fe76c12f7174ac5018054c'),
            "quantity": 1,
            "_id": ObjectId('56fe76c12f7174ac50180552')
        }
    ],
    "__v": 1
}
Run Code Online (Sandbox Code Playgroud)

Bla*_*ven 16

您需要在“项目”在这里比赛,因为所有的MongoDB的查询做的就是寻找一个“文件”具有“至少一个元素”“大于”你问的条件。

因此过滤“数组”与您拥有的“查询”条件不同。

一个简单的“投影”只会将“第一个”匹配项返回到该条件。所以这可能不是你想要的,但作为一个例子:

Order.find({ "articles.quantity": { "$gte": 5 } })
    .select({ "articles.$": 1 })
    .populate({
        "path": "articles.article",
        "match": { "price": { "$lte": 500 } }
    }).exec(function(err,orders) {
       // populated and filtered twice
    }
)
Run Code Online (Sandbox Code Playgroud)

这种“某种”可以满足您的需求,但问题实际上是最多只会返回数组中的一个元素"articles"

要正确执行此操作,您需要.aggregate()过滤数组内容。理想情况下,这是通过 MongoDB 3.2 和$filter. 但这里也有一种特殊的方式.populate()

Order.aggregate(
    [
        { "$match": { "artciles.quantity": { "$gte": 5 } } },
        { "$project": {
            "orderdate": 1,
            "articles": {
                "$filter": {
                    "input": "$articles",
                    "as": "article",
                    "cond": {
                       "$gte": [ "$$article.quantity", 5 ]
                    }
                }
            },
            "__v": 1
        }}
    ],
    function(err,orders) {
        Order.populate(
            orders.map(function(order) { return new Order(order) }),
            {
                "path": "articles.article",
                "match": { "price": { "$lte": 500 } }
            },
            function(err,orders) {
                // now it's all populated and mongoose documents
            }
        )
    }
)
Run Code Online (Sandbox Code Playgroud)

所以这里发生的是数组的实际“过滤”发生在.aggregate()语句中,但当然由此产生的结果不再是“猫鼬文档”,因为一方面.aggregate()它可以“改变”文档结构,并且对于这个原因猫鼬“假设”是这种情况,只是返回一个“普通对象”。

这不是真正的问题,因为当您看到$project舞台时,我们实际上是根据定义的模式要求文档中存在的所有相同字段。因此,即使它只是一个“普通对象”,将它“转换”回猫鼬文档也没有问题。

这就是.map()进来的地方,因为它返回一组转换后的“文档”,这对于下一阶段很重要。

现在您调用Model.populate()which 然后可以在“猫鼬文档数组”上运行进一步的“人口”。

结果最终就是你想要的。


MongoDB 比 3.2.x 旧的版本

这里唯一真正改变的是聚合管道,所以为了简洁起见,这就是所有需要包含的内容。

MongoDB的2.6 -可与组合滤波器阵列$map$setDifference。结果是一个“集合”,但是当 mongoose_id默认在所有子文档数组上创建一个字段时,这不是问题:

    [
        { "$match": { "artciles.quantity": { "$gte": 5 } } },
        { "$project": {
            "orderdate": 1,
            "articles": {
                "$setDiffernce": [
                   { "$map": {
                      "input": "$articles",
                      "as": "article",
                      "in": {
                         "$cond": [
                             { "$gte": [ "$$article.price", 5 ] },
                             "$$article",
                             false
                         ]
                      }
                   }},
                   [false]
                ]
            },
            "__v": 1
        }}
    ],
Run Code Online (Sandbox Code Playgroud)

比这更旧的修订版必须使用$unwind

    [
        { "$match": { "artciles.quantity": { "$gte": 5 } }},
        { "$unwind": "$articles" },
        { "$match": { "artciles.quantity": { "$gte": 5 } }},
        { "$group": {
          "_id": "$_id",
          "orderdate": { "$first": "$orderdate" },
          "articles": { "$push": "$articles" },
          "__v": { "$first": "$__v" }
        }}
    ],
Run Code Online (Sandbox Code Playgroud)

$lookup 替代方案

另一种替代方法是只在“服务器”上执行所有操作。这是$lookupMongoDB 3.2 及更高版本的一个选项:

Order.aggregate(
    [
        { "$match": { "artciles.quantity": { "$gte": 5 } }},
        { "$project": {
            "orderdate": 1,
            "articles": {
                "$filter": {
                    "input": "$articles",
                    "as": "article",
                    "cond": {
                       "$gte": [ "$$article.quantity", 5 ]
                    }
                }
            },
            "__v": 1
        }},
        { "$unwind": "$articles" },
        { "$lookup": {
            "from": "articles",
            "localField": "articles.article",
            "foreignField": "_id",
            "as": "articles.article"
        }},
        { "$unwind": "$articles.article" },
        { "$group": {
          "_id": "$_id",
          "orderdate": { "$first": "$orderdate" },
          "articles": { "$push": "$articles" },
          "__v": { "$first": "$__v" }
        }},
        { "$project": {
            "orderdate": 1,
            "articles": {
                "$filter": {
                    "input": "$articles",
                    "as": "article",
                    "cond": {
                       "$lte": [ "$$article.article.price", 500 ]
                    }
                }
            },
            "__v": 1
        }}
    ],
    function(err,orders) {

    }
)
Run Code Online (Sandbox Code Playgroud)

尽管这些只是简单的文档,但它的结果与您从该.populate()方法中得到的结果相同。当然,如果你真的必须,你可以在所有情况下再次“投射”到猫鼬文档。

“最短”路径

这真的可以追溯到原始语句,您基本上只是“接受”“查询”并不意味着“过滤”数组内容。该.populate()可happilly这样做becuse它只是一个“查询”,并在方便的“文档”馅。

因此,如果您确实没有通过删除原始文档数组中的其他数组成员来节省带宽的“bucketloads”,那么.filter()在后处理代码中将它们取出:

Order.find({ "articles.quantity": { "$gte": 5 } })
    .populate({
        "path": "articles.article",
        "match": { "price": { "$lte": 500 } }
    }).exec(function(err,orders) {
        orders = orders.filter(function(order) {
            order.articles = order.articles.filter(function(article) {
                return (
                    ( article.quantity >= 5 ) &&
                    ( article.article != null )
                )
            });
            return order.aricles.length > 0;
        })

        // orders has non matching entries removed            
    }
)
Run Code Online (Sandbox Code Playgroud)

  • 我不想表现得忘恩负义,我只是说代码中存在语法错误,如果其他人可能会找到此线程并复制/粘贴您的解决方案。我当然感谢您的努力和时间。我会接受你的回答。 (2认同)