【问题标题】:Using MongoDB $where to compare elements from Array使用 MongoDB $where 比较 Array 中的元素
【发布时间】:2017-09-22 17:33:45
【问题描述】:

假设我有以下两个 MongoDB 文档:

{ 
"_id" : ObjectId(a59b0e19aff8a2ed2128bef97"), 
"name" : "John", 
"matches" : [
    {
        "name" : "Bob", 
        "count" : 10
    }, 
    {
        "name" : "John", 
        "count" : 20
    }, 
    {
        "name" : "Alice", 
        "count" : 30
    }
 ]
}


{ 
"_id" : ObjectId(b59b0e19aff8a2ed2128bef97"), 
"name" : "Mike", 
"matches" : [
    {
        "name" : "Bob", 
        "count" : 10
    }, 
    {
        "name" : "John", 
        "count" : 20
    }, 
    {
        "name" : "Alice", 
        "count" : 30
    }
 ]
}

我需要创建 MongoDB 查询,将“name”与“matches.name”进行比较。

在我的示例中,只有第一个文档会被匹配,因为“John”在“matches”数组中。 第二个文档将不匹配,因为 Mike 不在数组中。

我试过{$where : "this.matches.name == this.name"},但这不起作用。

有什么想法吗?

【问题讨论】:

  • 你想要mongo查询还是js代码可以?因为如果你已经在某个变量中加载了文档,那么js代码会更合适
  • 不,我想要 mongo 查询。在这种情况下,当文档已经加载时,JS 解决方案很简单。

标签: javascript arrays mongodb


【解决方案1】:

我相信这可能是您正在寻找的,aggregate 查询通过 matches.$.name 查看是否匹配 $name

db.collection.aggregate([{
            "$redact": {
                "$cond": [{
                        "$anyElementTrue": [{
                                "$map": {
                                    "input": "$matches",
                                    "as": "matches",
                                    "in": {
                                        "$eq": ["$$matches.name", "$name"]
                                    }
                                }
                            }
                        ]
                    },
                    "$$KEEP",
                    "$$PRUNE"
                ]
            }
        }
        ])

巧妙地返回

{ 
    "_id" : ObjectId("59c54e6f505e2f07180e60f7"), 
    "name" : "John", 
    "matches" : [
        {
            "name" : "Bob", 
            "count" : 10.0
        }, 
        {
            "name" : "John", 
            "count" : 20.0
        }, 
        {
            "name" : "Alice", 
            "count" : 30.0
        }
    ]
}

【讨论】:

  • 谢谢@Skami。这个解决方案做得很好!
【解决方案2】:

你尝试过这种函数式查询方法吗?

db.myCollection.find( { $where: function() { return (this.matches.name == this.name) } } );

如果这适用于您的场景,请在此处发表评论:)

【讨论】:

  • {$where : "this.matches.name == this.name"}一样,这个查询不返回任何文档
猜你喜欢
  • 2023-02-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多