2017-09-22 52 views
0

元素让我们假设我有两个以下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查询,将比较“名”与“matches.name”。

在我的示例中,只有第一个文档才会匹配,因为“John”位于“matches”数组中。 由于Mike不在阵列中,第二个文档将不匹配。我试过{$where : "this.matches.name == this.name"}但这不起作用。

任何想法?

+0

你想蒙戈查询或JS代码会做什么?因为如果你已经在一些变量中加载了文件,一个js代码会更合适 – Prasanna

+0

不,我想mongo查询。 JS解决方案在这种情况下很简单,当文件已经加载。 –

回答

0

我认为这可能是你在找什么,一个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 
     } 
    ] 
} 
+0

谢谢@Skami。这个解决方案非常好! –

-1

你试试这个功能查询方法?

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

如果正在为您的情况,请在这里评论:)

+0

与'{其中:“this.matches.name == this.name”}'相同,并且此查询不返回任何文档 –