Javascript 使用MongoDB$where比较数组中的元素
假设我有以下两个MongoDB文档:Javascript 使用MongoDB$where比较数组中的元素,javascript,arrays,mongodb,Javascript,Arrays,Mongodb,假设我有以下两个MongoDB文档: { "_id" : ObjectId(a59b0e19aff8a2ed2128bef97"), "name" : "John", "matches" : [ { "name" : "Bob", "count" : 10 }, { "name" : "John", "count" : 20 }, { "name" : "Alic
{
"_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”}
但这不起作用
有什么想法吗?我相信这可能就是您正在寻找的,一个
聚合查询,查看匹配项。$.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
}
]
}
您尝试过这种函数查询方法吗
db.myCollection.find( { $where: function() { return (this.matches.name == this.name) } } );
如果这适用于您的场景,请在此处发表评论:)您想要mongo查询还是js代码?因为如果您已经在某个变量中加载了文档,那么js代码会更合适。不,我想要mongo查询。在已经加载文档的情况下,JS解决方案很简单。它与{$where:“this.matches.name==this.name”}
相同,并且此查询不返回任何DocumentsHanks@Skami。这个解决方案做得很好!