Mongodb查询:使用未知父级的嵌套值进行查询

时间:2015-11-10 23:46:40

标签: mongodb mongodb-query

我数据库中的记录结构如下:

{"_id": "2", children: {"JeFF": {age: 8}, "BilL": {age: 4}}}

我正在寻找一个查询,允许我查找包含特定孩子年龄的文档。例如,如果我将“4”作为参数传递,我希望得到以下结果:

func applicationDidBecomeActive(application: UIApplication) {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    socket.reconnect()

}

func applicationDidEnterBackground(application: UIApplication) {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    socket.close()
}

不幸的是,重构我倾倒的整个架构超出了我的项目范围。我很欣赏任何见解

1 个答案:

答案 0 :(得分:0)

您可以使用$where运算符查找记录。此运算符速度不快,但会返回您所追踪的记录。它使用JavaScript函数迭代子对象中的键,并检查该键的年龄是否匹配。

 db.data.find({
   $where: function() {
     for (var key in this.children)  {
       if (this.children[key].age ===4){
       return true;
        }
     }
     return false;
   }
 })