gpt4 book ai didi

mongodb - 从 mgo (golang+MongoDB) 中的嵌入式数组中检索元素

转载 作者:数据小太阳 更新时间:2023-10-29 03:14:48 26 4
gpt4 key购买 nike

我在后端使用 golang,并使用 mongoDB 作为数据库。当我尝试从其中一个嵌入式数组中检索文档时,我在结果中只获得了嵌入式数组的一个索引。

我的结构是这样的

type (
Employee struct {
Name string
EmpId string
Password string
Leave []*LeaveInfo
}
LeaveInfo struct {

Id int
Days float64
From time.Time
To time.Time
AppliedDate time.Time
Status string
ApprovedDate time.Time
}

我的golang代码是

   t := time.Date(2016, 10, 1, 0, 0, 0, 0, time.UTC)
var result []*Employee
if e := c.Find(nil).Select(bson.M{"leave": bson.M{
"$elemMatch": bson.M{
"from": bson.M{
"$gte":t,
},
},
},
},
).All(&result); e != nil {
fmt.Println(e)
}

我的数据库结构是

_id:57d7a6673897593ae84bed49{
Name:"Mark"
EmpId:"E123"
Password:1234
Leave:[
{
"id" : 0,
"days" : 1.5,
"from" : ISODate("2016-12-01T00:00:00Z"),
"to" : ISODate("2016-12-02T12:00:00Z"),
"applieddate" : ISODate("0001-01-01T00:00:00Z"),
"status" : "Approved",
"approveddate" : ISODate("0001-01-01T00:00:00Z"),

},
{

"id" : 1,
"days" : 2.0,
"from" : ISODate("2016-12-11T00:00:00Z"),
"to" : ISODate("2016-12-12T00:00:00Z"),
"applieddate" : ISODate("0001-01-01T00:00:00Z"),
"status" : "Approved",
"approveddate" : ISODate("0001-01-01T00:00:00Z"),

},
]
}

在这里,我只得到 Leave 数组的索引 0。正如你所看到的,数组的两个索引都有大于 t 的日期。但是当我检索它时,我只得到一个索引(索引 0)。但是我需要的是检索所有日期大于 t 的索引。请帮助我。谢谢

我的结果如下

{
"Name": "",

"EmpId": "",
"Password": "",
"Leave": [
{

"Id": 0,
"Days": 1.5,
"from" : ISODate("2016-12-01T00:00:00Z"),
"to" : ISODate("2016-12-02T12:00:00Z"),
"applieddate" : ISODate("0001-01-01T00:00:00Z"),
"status" : "Approved",
"approveddate" : ISODate("0001-01-01T00:00:00Z"),
}
]
}

最佳答案

我不确定在单个 mongo 查询中是否可以实现您的要求。我宁愿得到所有元素和过滤器是这样的:

var result []*Employee
err := c.Find(nil).All(&result)
if err != nil {
// do stuff...
}

// For each result, filter the Leave values having a to small From value.
t := time.Date(2016, 10, 1, 0, 0, 0, 0, time.UTC)
for i := range result {
var j int
for j < len(result[i].Leave) {
if result[i][j].From.Before(t) {
result[i] = append(result[i][:j], result[i][j+1:]...)
continue
}
j++
}
}

关于mongodb - 从 mgo (golang+MongoDB) 中的嵌入式数组中检索元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39464370/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com