gpt4 book ai didi

mongodb - 获取 MongoDB 文档 WHERE 状态和日期之间

转载 作者:行者123 更新时间:2023-12-01 22:21:19 26 4
gpt4 key购买 nike

我需要从订单中获取所有文件 在哪里 :

status == 'paid' AND status == 'delivered' AND
closed_at BETWEEN startDate AND endDate ;
我已经使用以下代码访问了我的 mongoDB 连接:
package main

import (
"context"
"fmt"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"go.mongodb.org/mongo-driver/mongo/readpref"
"time"
)

func main() {
mx, err := time.LoadLocation("America/Mexico_City")
endDate := time.Now().In(mx)
startDate := endDate.AddDate(0, 0, -1)

if err != nil { fmt.Println(err); return }

client, err := mongo.NewClient(options.Client().ApplyURI("mongodb+srv://<userName>:<pass>@someDomain/orders"))
if err != nil { fmt.Println(err); return }

ctx, _ := context.WithTimeout(context.Background(), 10*time.Second)
err = client.Connect(ctx)
if err != nil { fmt.Println(err); return }
defer client.Disconnect(ctx)

err = client.Ping(ctx, readpref.Primary())
if err != nil { fmt.Println(err); return }

orders := client.Database("orders").Collection("orders") //here I want to filter with the status 'paid' and 'delivered' and closerd_at between dates.
}

func Bod(t time.Time) time.Time {
year, month, day := t.Date()
return time.Date(year, month, day, 0, 0, 0, 0, t.Location())
}
我对文档还有一件事表示怀疑, closed_at有一个格式日期,如:
2020-04-23T21:28:46.642+00:00
还有我的 fromto日期的格式如下:
startDate: 2020-08-06 00:00:00 -0500 CDT
endDate: 2020-08-07 00:00:00 -0500 CDT

最佳答案

这是我的解决方案:

query := bson.M{
"status": bson.M{"$in":[]string{"paid","delivered"}}, //only status paid and delivered
"closed_at": bson.M{"$gt": from, "$lt": to}, //between dates
}

cursor, err := client.Database("orders").Collection("orders").Find(ctx,query)
引用答案: MongoDB Compass Filter expression to Go bson.M expression

关于mongodb - 获取 MongoDB 文档 WHERE 状态和日期之间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63309506/

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