【问题标题】:How to find all elements of a collection in an array that matches two conditions如何在匹配两个条件的数组中查找集合的所有元素
【发布时间】:2014-04-29 12:22:27
【问题描述】:

我一直在看this documentation,并尝试在这里实现它:

customers.find({'name':tenantName,'scripts.author':author},'scripts',function(err,data2){

但这并没有找到我想要它找到的东西。无论scripts.author 是否匹配,我都会取回scripts 的每个元素。

我做错了什么?

我的数据是这样的

{
name: "something"
scripts:[
    {author:"something", data:"data"},
    {author:"something else" data:"data2"},
    {author:"something", data:"data3"}
        ]
}

我想得到所有的scripts author 匹配我给它的地方

【问题讨论】:

    标签: javascript node.js mongodb mongoose aggregation-framework


    【解决方案1】:

    关于在这样的查询中进行匹配,您需要了解一些问题。首先,你想要做的是:

    customer.find(
        { "name":tenantName, "scripts.author": author },
        { "scripts.$" },
        function(err,data2) {
    
          // work here
    })
    

    这将使用positional $ 运算符来匹配元素。但这里的问题是它只会匹配数组的 first 元素。这在文档中有所介绍。结果会是这样的:

    { "scripts" : [  {  "author" : "something",  "data" : "data" } ] }
    

    如果你需要匹配多个元素,那么你需要使用聚合函数来过滤数组内容:

    customer.aggregate([
    
        // Match just the documents you want
        { "$match": { "name": tenantName, "scripts.author": author } },
    
        // Unwind the array
        { "$unwind": "$scripts" },
    
        // Match to filter just the array elements
        { "$match": { "scripts.author": author } },
    
        // Push back the array elements
        { "$group": {
            "_id": "$_id",
            "name": { "$first": "$name" },
            "scripts": { "$push": "$scripts" }
        }}
    
    ],
    function(err,result) {
    
    })
    

    结果将有两个元素匹配“某事”作为author

    为什么这一切?那么上面提到的投影可以做什么是有限制的。但主要原因是您匹配数组中的元素,但您匹配的是“包含”文档匹配数组中的元素。

    所以如果你真的想过滤结果,这就是你的做法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-30
      • 1970-01-01
      • 1970-01-01
      • 2021-09-07
      • 1970-01-01
      相关资源
      最近更新 更多