如果您对c#–在MongoDB中查询id-s包含在列表中的文档和mongodb查询语句怎么写感兴趣,那么这篇文章一定是您不可错过的。我们将详细讲解c#–在MongoDB中查询id-s包含在列表中的文档
如果您对c# – 在MongoDB中查询id-s包含在列表中的文档和mongodb查询语句怎么写感兴趣,那么这篇文章一定是您不可错过的。我们将详细讲解c# – 在MongoDB中查询id-s包含在列表中的文档的各种细节,并对mongodb查询语句怎么写进行深入的分析,此外还有关于c# – 在MongoDb中查询超时、Golang无法在MongoDB中创建文档、Go语言(mgo)删除MongoDB中的文档、mongodb中查询返回指定字段的实用技巧。
本文目录一览:- c# – 在MongoDB中查询id-s包含在列表中的文档(mongodb查询语句怎么写)
- c# – 在MongoDb中查询超时
- Golang无法在MongoDB中创建文档
- Go语言(mgo)删除MongoDB中的文档
- mongodb中查询返回指定字段
c# – 在MongoDB中查询id-s包含在列表中的文档(mongodb查询语句怎么写)
我应该为每个查询调用一个查询,还是应该指定一个巨大的OR查询?可能有一些我不知道的更好的方法
解决方法
db.co.find({_id:{$in:[id1,id2,id3,..,idN]}})
c# – 在MongoDb中查询超时
解决方法
http://www.mongodb.org/display/DOCS/Viewing+and+Terminating+Current+Operation
或者,在新客户端启动时,您可以执行更具编程性的操作(从日志中获取最后运行的查询,因为它们来自以前的客户端而终止它们).您是否可以通过编程方式识别要杀死的操作并避免杀死其他操作是关键 – 可能需要您在应用中添加一些日志记录以跟踪正在进行的操作.
Golang无法在MongoDB中创建文档
问题内容
我正在尝试将文档插入 mongodb,但尽管成功连接到 mongo,但我仍然收到以下错误:
http: panic serving 172.27.0.8:40176: runtime error: invalid memory address or nil pointer dereference
我正在初始化数据库连接的 main.go 看起来像这样
func main(){ //connect to mongo mongoclient,err:=connecttomongo() if err!=nil{ log.panic(err) } client=mongoclient //create a context that mongo needs in order to disconnect ctx,_:=context.withtimeout(context.background(), 15*time.second) // ctx,cancel:=context.withtimeout(context.background(), 15*time.second) //defer cancel() //close connection defer func () { if err =client.disconnect(ctx); err!=nil{ panic(err) } }() muxrouter := mux.newrouter().strictslash(true) //specify who''s allowed to connect c:=cors.new(cors.options{ allowedorigins: []string{"https://*", "http://*"}, allowedmethods: []string{"get", "post", "put", "delete", "options"}, allowedheaders: []string{"accept", "authorization", "content-type", "x-csrf-token"}, exposedheaders: []string{"link"}, allowcredentials: true, maxage: 300, }) router := addroutes(muxrouter) handler := c.handler(router) log.println("service stratring at o port ",webport) sterr := http.listenandserve(":9090", handler) //uncomment this line when using docker if sterr != nil { log.fatal("error starting http server :: ", err) return } log.println("service started at port ",webport) } func connecttomongo()(*mongo.client,error){ mongousername := os.getenv("mongousername") mongopassword := os.getenv("mongopassword") //create connection options clientoptions:=options.client().applyuri(mongourl) clientoptions.setauth(options.credential{ username: mongousername, password: mongopassword, }) //connect c,err:=mongo.connect(context.todo(),clientoptions) if err!=nil{ log.println("error connecting to mongo",err) return nil,err } log.println("connected to mongo") return c,nil }
在一个单独的文件 models.go 中,我尝试将数据插入数据库,如下所示:
var client *mongo.Client func Insert(entry LogEntry)error{ log.Printf("Attempting to insert %s", entry) log.Printf("client s %s", client) //db:=client.Database("logs") //log.Printf("database is %s", db) collection:=client.Database("logs").Collection("logsCollection") log.Printf("collection is %s", collection) _,err :=collection.InsertOne(context.TODO(), LogEntry{ Name: entry.Name, Data: entry.Data, CreatedAt: time.Now(), UpdatedAt: time.Now(), }) if err!=nil{ log.Println("Error inserting new record into logs collection",err) return err } log.Println("insert successful") return nil }
有人能发现我做错了什么吗?
立即学习“go语言免费学习笔记(深入)”;
解决方法
由于错误是通用的(例如,未提供错误的行号),我将分享一个可行的解决方案,也许可以帮助您找出问题所在。我先分享一下代码。
main.go 文件
package main import ( "context" "fmt" "time" "go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/mongo" "go.mongodb.org/mongo-driver/mongo/options" ) type LogEntry struct { Name string Data string CreatedAt time.Time UpdatedAt time.Time } func main() { ctx, cancel := context.WithTimeout(context.Background(), time.Second*20) defer cancel() clientOptions := options.Client().ApplyURI("mongodb://root:root@localhost:27017") mongoClient, err := mongo.Connect(ctx, clientOptions) if err != nil { panic(err) } defer mongoClient.Disconnect(ctx) demoDb := mongoClient.Database("demodb") myCollection := demoDb.Collection("myCollection") // delete documents if _, err := myCollection.DeleteMany(ctx, bson.M{}); err != nil { panic(err) } // insert data insertRes, err := myCollection.InsertOne(ctx, LogEntry{ Name: "lorem ipsum", Data: "lorem ipsum", CreatedAt: time.Now(), UpdatedAt: time.Now(), }) if err != nil { panic(err) } fmt.Println(insertRes.InsertedID) // query data cursor, err := myCollection.Find(ctx, bson.M{}) if err != nil { panic(err) } var logEntries []bson.M if err = cursor.All(ctx, &logEntries); err != nil { panic(err) } for _, v := range logEntries { fmt.Println(v) } }
为了演示,我将所有逻辑放在一个文件中。在此文件中,我执行了以下步骤:
- 设置 mongodb 连接。
- 连接到数据库以及该数据库中的集合。
- 删除所有已有的文档(只是为了更清晰)。
- 在 mycollection 集合中插入新的 logentry 实例。
- 检索 mycollection 集合中的所有条目。
最后要提到的是我用来运行容器的 docker 命令:
docker运行-d -p 27017:27017 --name mymongo -e mongo_initdb_root_username=root -e mongo_initdb_root_password=root mongo:latest
如果您坚持使用我的解决方案,您应该能够毫无问题地插入文档。如果不是这样,请告诉我,我会尽力帮助您!
以上就是Golang无法在MongoDB中创建文档的详细内容,更多请关注php中文网其它相关文章!
Go语言(mgo)删除MongoDB中的文档
在golang中使用mgo连接mongodb进行文档操作时,删除文档是经常需要做的操作。这篇文章将为您介绍如何使用mgo实现删除mongodb中的文档。
删除文档
删除单个文档
首先,我们来看如何使用mgo删除单个文档。
session, err := mgo.Dial("localhost:27017") if err != nil { panic(err) } defer session.Close() // 选择数据库和集合 collection := session.DB("test_db").C("test_collection") err = collection.Remove(bson.M{"name": "John"}) if err != nil { panic(err) }
在这个例子中,我们连接到MongoDB,选择了数据库"test_db"和集合"test_collection"。然后,我们使用bson.M创建一个匹配查询,找到了名字为"John"的文档,并使用collection.Remove()方法将其删除。如果删除失败,我们将会抛出一个异常报错。
立即学习“go语言免费学习笔记(深入)”;
删除多个文档
如果你需要删除多个文档,你可以使用collection.RemoveAll()方法。
session, err := mgo.Dial("localhost:27017") if err != nil { panic(err) } defer session.Close() // 选择数据库和集合 collection := session.DB("test_db").C("test_collection") _, err = collection.RemoveAll(bson.M{"gender": "male"}) if err != nil { panic(err) }
在这个例子中,我们使用bson.M创建一个查询,找到了所有性别为"male"的文档,并使用collection.RemoveAll()方法将它们全部删除。
删除集合
如果你想彻底删除一个集合并释放其内存和硬盘空间,你可以使用collection.Drop()方法。
session, err := mgo.Dial("localhost:27017") if err != nil { panic(err) } defer session.Close() // 选择数据库和集合 collection := session.DB("test_db").C("test_collection") err = collection.Drop() if err != nil { panic(err) }
在这个例子中,我们使用collection.Drop()方法删除了"test_collection"集合。注意,所有文档都将被永久删除。
总结
在Golang中使用mgo连接MongoDB进行文档操作时,删除文档是一项经常需要做的操作。删除单个文档可以使用collection.Remove()方法,删除多个文档可以使用collection.RemoveAll()方法,而彻底删除一个集合则可以使用collection.Drop()方法。
希望这篇文章能够帮助你在Golang中使用mgo删除MongoDB中的文档。
以上就是Go语言(mgo)删除MongoDB中的文档的详细内容,更多请关注php中文网其它相关文章!
mongodb中查询返回指定字段
mongodb中查询返回指定字段
在写vue项目调用接口获取数据的时候,比如新闻列表页我只需要显示新闻标题和发表时间,点击每条新闻进入详情页的时候才会需要摘要、新闻内容等关于此条新闻的所有字段。
但其实我所有关于新闻的数据在同一个数据集合里,也就是只有一个集合
我不希望获取新闻列表的时候就把每条新闻的所有数据都显示
我也不希望是建两个集合分别放列表数据和详情数据
所以这篇文章对我很有帮助:MongoDB查询操作限制返回字段的方法
//只输出id和title字段,第一个参数为查询条件,空代表查询所有
db.news.find( {}, { id: 1, title: 1 } ) //如果需要输出的字段比较多,不想要某个字段,可以用排除字段的方法 //不输出内容字段,其它字段都输出 db.news.find( {}, {content: 0 } )
想了解详细内容可参照上方原文。我这里只是对自己项目需求的简单纪录。方法亲测有效。
MongoDB查询操作限制返回字段的方法
返回匹配文档的所有字段:
如果没有指定projection,find()方法返回所有匹配文档的所有字段。
1
|
db.inventory.find( { type:
''food''
} )
|
这个例子将返回inventory集合中type字段的值为"food"的所有文档,返回的文档包含全部字段。
返回指定字段和_id字段:
一个projection可以明确地指定多个字段。下面的操作中,find()方法返回匹配的所有文档。在结果集中,只有item和qty字段,默认_id字段也是返回的。
1
|
db.inventory.find( { type:
''food''
}, { item:
1
, qty:
1
} )
|
可以通过在projection中指定排除_id字段将其从结果中去掉,如下例子所示:
1
|
db.inventory.find( { type:
''food''
}, { item:
1
, qty:
1
, _id:
0
} )
|
返回除排除掉以外的字段:
可以使用一个projection排除一个或者一组字段,如下:
1
|
db.inventory.find( { type:
''food''
}, { type:
0
} )
|
这个操作返回所有type字段值为food的文档,在结果中type字段不返回。
数组字段的projection:
elemMatch和elemMatch和slice运算符是对数组进行projection的唯一途径。
关于c# – 在MongoDB中查询id-s包含在列表中的文档和mongodb查询语句怎么写的问题就给大家分享到这里,感谢你花时间阅读本站内容,更多关于c# – 在MongoDb中查询超时、Golang无法在MongoDB中创建文档、Go语言(mgo)删除MongoDB中的文档、mongodb中查询返回指定字段等相关知识的信息别忘了在本站进行查找喔。
本文标签: