Does MongoDB's $in clause guarantee order

后端 未结 10 1415
春和景丽
春和景丽 2020-11-22 01:39

When using MongoDB\'s $in clause, does the order of the returned documents always correspond to the order of the array argument?

10条回答
  •  自闭症患者
    2020-11-22 02:16

    This is a code solution after the results are retrieved from Mongo. Using a map to store index and then swapping values.

    catDetails := make([]CategoryDetail, 0)
    err = sess.DB(mdb).C("category").
        Find(bson.M{
        "_id":       bson.M{"$in": path},
        "is_active": 1,
        "name":      bson.M{"$ne": ""},
        "url.path":  bson.M{"$exists": true, "$ne": ""},
    }).
        Select(
        bson.M{
            "is_active": 1,
            "name":      1,
            "url.path":  1,
        }).All(&catDetails)
    
    if err != nil{
        return 
    }
    categoryOrderMap := make(map[int]int)
    
    for index, v := range catDetails {
        categoryOrderMap[v.Id] = index
    }
    
    counter := 0
    for i := 0; counter < len(categoryOrderMap); i++ {
        if catId := int(path[i].(float64)); catId > 0 {
            fmt.Println("cat", catId)
            if swapIndex, exists := categoryOrderMap[catId]; exists {
                if counter != swapIndex {
                    catDetails[swapIndex], catDetails[counter] = catDetails[counter], catDetails[swapIndex]
                    categoryOrderMap[catId] = counter
                    categoryOrderMap[catDetails[swapIndex].Id] = swapIndex
                }
                counter++
            }
        }
    }
    

提交回复
热议问题