如何使用“查找”查询mongoDB

如何使用“查找”查询mongoDB

问题描述:

I have this problem. I have this dataBase in 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.

For example if I choose Susan i would like to have an array with ["class 1" , ["class 2"].

I have used findOne but this time i need to use find.

我有这个问题。 我在mongoDB中有这个数据库: p>

  {
“_id”:ObjectId(“585fe33d3c63b4a81e00002b”),
“class”:[
 {
“name”  :“class 1”,
“people”:[
 {
“id”:“58596”,
“name”:“mark”,
},
 {
“id”:“  45643“,
”name“:”Susan“,
},
 {
”id“:”85952“,
”name“:”Loris“,
} 
},
 {  
“名称”:“2级”,
“人”:[
 {
“id”:“58456”,
“名称”:“Sissi”,
},
 {
  “id”:“45643”,
“名称”:“苏珊”,
} 
] 
} 
 
 
} 
} 
  code>  pre> 
 
 

我使用php并且我想知道具有特定名称的类的名称并将它们保存在数组中。 p>

例如,如果我选择Susan我想要一个数组 用 [“class 1”, [“class 2”] code>。 p>

我使用过findOne,但这次我需要使用find。 p> div>

You can make use of MongoDB aggregation framework.

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.

Refer Aggregation Pipeline Optimization for improved performance.