简体   繁体   中英

How to query mongoDB with the “find”

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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