瀏覽代碼

排序由map无须改为有序

wangchuanjin 4 年之前
父節點
當前提交
399a92c2d9
共有 1 個文件被更改,包括 18 次插入4 次删除
  1. 18 4
      src/mongodb/mongodb.go

+ 18 - 4
src/mongodb/mongodb.go

@@ -16,6 +16,7 @@ import (
 	"go.mongodb.org/mongo-driver/bson/primitive"
 	"go.mongodb.org/mongo-driver/mongo"
 	"go.mongodb.org/mongo-driver/mongo/options"
+	"go.mongodb.org/mongo-driver/mongo/readpref"
 )
 
 func NewMgo(addr, db string, size int) *MongodbSim {
@@ -251,15 +252,15 @@ func (ms *MgoSess) Iter() *MgoIter {
 	}
 	find.SetBatchSize(100)
 	if len(ms.sorts) > 0 {
-		sort := bson.M{}
+		sort := bson.D{}
 		for _, k := range ms.sorts {
 			switch k[:1] {
 			case "-":
-				sort[k[1:]] = -1
+				sort = append(sort, bson.E{k[1:], -1})
 			case "+":
-				sort[k[1:]] = 1
+				sort = append(sort, bson.E{k[1:], 1})
 			default:
-				sort[k] = 1
+				sort = append(sort, bson.E{k, 1})
 			}
 		}
 		find.SetSort(sort)
@@ -772,3 +773,16 @@ func autoUpdateTime(db, coll string, ue *bson.M) {
 		(*ue)["$set"] = set
 	}
 }
+
+func (ms *MgoSess) ExampleDatabase_RunCommand() {
+	// run an explain command to see the query plan for when a "find" is executed on collection "bar"
+	// specify the ReadPreference option to explicitly set the read preference to primary
+	findCmd := bson.D{{"find", ms.coll}, {"projectid", "5f6bc002499cb0822d7e3322"}}
+	command := bson.D{{"explain", findCmd}}
+	opts := options.RunCmd().SetReadPreference(readpref.Primary())
+	var result bson.M
+	if err := ms.M.C.Database(ms.db).RunCommand(context.TODO(), command, opts).Decode(&result); err != nil {
+		log.Fatal(err)
+	}
+	fmt.Println(result)
+}