简体   繁体   English

如何使用“查找”查询mongoDB

[英]How to query mongoDB with the “find”

I have this problem. 我有这个问题。 I have this dataBase in mongoDB: 我在mongoDB中有以下数据库:

{
"_id" : ObjectId("585fe33d3c63b4a81e00002b"),
"class" : [ 
    {
        "name" : "class 1",
        "people" : [ 
            {
                "id" : "58596",
                "name" : "mark",
            }, 
            {
                "id" : "45643",
                "name" : "Susan",
            }, 
            {
                "id" : "85952",
                "name" : "Loris",
            }
    },      
    {
        "name" : "class 2",
        "people" : [ 
            {
                "id" : "58456",
                "name" : "Sissi",
            }, 
            {
                "id" : "45643",
                "name" : "Susan",
            }
        ]       
    }
]
}

I use php and I would like to know the names of the class with a specific name inside and save them in an array. 我使用php,我想知道内部具有特定名称的类的名称,并将其保存在数组中。

For example if I choose Susan i would like to have an array with ["class 1" , ["class 2"] . 例如,如果我选择Susan,我希望有一个带有["class 1" , ["class 2"]的数组。

I have used findOne but this time i need to use find. 我使用过findOne,但是这次我需要使用find。

You can make use of MongoDB aggregation framework . 您可以使用MongoDB聚合框架

Here is a query which will give you the date in the desired form. 这是一个查询,它将以所需的形式为您提供日期。 However, I believe that there will be some better and efficient way to handle this but this is what I came up with. 但是,我相信会有一些更好,更有效的方法来解决此问题,但这就是我想出的。

db.collection.aggregate([
  {"$unwind":"$class"},
  {"$unwind":"$class.people"},
  {"$match": {
      "class.people.name":"Susan"
       }
  },
  {"$group":{
      "_id":"$class.people.name",
      "classes":{"$push":"$class.name"}
    }
  }
])

Result :- 结果:-

{ "_id" : "Susan", "classes" : [ "class 1", "class 2" ] }

Try to $match before first $unwind operation to avoid the unnecessary results in the pipeline before $unwind . 尝试在第一个$unwind操作之前进行$match ,以避免$unwind之前管道中不必要的结果。

Refer Aggregation Pipeline Optimization for improved performance. 有关改进的性能,请参阅聚合管道优化

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM