如何在Golang中构造动态Mongo查询

时间:2020-11-05 07:31:23

标签: mongodb go

我要根据用户条件(动态)过滤员工记录

For Ex: 
[
map[condition:Admin condition_symbol:OR filter_by:Department operator_symbol:=] 
map[condition:User condition_symbol:AND filter_by:Department operator_symbol:=]
map[condition:01/01/2020 condition_symbol:"" filter_by:DOJ operator_symbol:>] 
]

我是mongodb的新手,我该如何构建它。 我尝试过并用Google搜索它,但没有用。

我需要mongo查询

MySQL Example : select * from employee where department="ADMIN" OR department="USER" AND DOJ > "01/01/2020"

动态

   Here I don't know the column name and conditions everything is dynamic, So
   Need to write the dynamic mongo query. 

预先感谢

2 个答案:

答案 0 :(得分:0)

如果我将您的SQL查询转换为mongo,它将变为:

db.getCollection("employee").find({
    $or: [{ department: "ADMIN" }, { department: "USER" }]
    DOJ: { $gte: "01/01/2020" }
})

然后将其转换为golang。管道查询将变为:

query := bson.M{
    "$or": []bson.M{ { department: "ADMIN" }, { department: "USER" } },
    "DOJ": bson.M{ "$gte": "01/01/2020" },
}

答案 1 :(得分:0)

用于您的mysql查询

SELECT * from employee 
 WHERE (department="ADMIN" OR department="USER") AND DOJ > "01/01/2020"

对应的MongoDB查询

db.getCollection('employee').find({
  $or: [
   {department: "ADMIN"},
   {department: "USER"}
  ],
 // take care for DOJ type is date or string
 'DOJ': { $gt: new Date("01/01/2020") }
})

请交叉检查go lang语法,我不经常使用go语言

// get employee collection instance from database
employeeCollection := client.Database("database").Collection("employee")
// create doj condition  
dojFilter:= bson.D{
  {"$gt": new Date("01/01/2020")}
}
// create query pipeline
pipeline := bson.D{
    {"DOJ", dojFilter},
    {"$or", []interface{}{
        bson.D{{"department", "ADMIN"}},
        bson.D{{"department", "USER"}},
    }},
}

data = employeeCollection.FindOne(context.TODO(), pipeline)