登录
首页 >  Golang >  Go问答

设计有效的 MongoDB 查询以获取格式正确的记录

来源:stackoverflow

时间:2024-03-15 15:42:25 194浏览 收藏

golang学习网今天将给大家带来《设计有效的 MongoDB 查询以获取格式正确的记录》,感兴趣的朋友请继续看下去吧!以下内容将会涉及到等等知识点,如果你是正在学习Golang或者已经是大佬级别了,都非常欢迎也希望大家都能给我建议评论哈~希望能帮助到大家!

问题内容

这里我想根据 parent 进行绑定数据的查询。我收到以下对象:

{
  "_id" : 1,
  "name" : "home",
  "slug" : "home",
  "parent" : 0,
  "description" : "this will direct you on home page",
  "order" : 1,
  "taxonomy" : "nav_bar"
}
{
  "_id" : 2,
  "name" : "links",
  "slug" : "links",
  "parent" : 0,
  "description" : "this will direct you on home page",
  "order" : 2,
  "taxonomy" : "nav_bar"
}
{
  "_id" : 3,
  "name" : "link1",
  "slug" : "link1",
  "parent" : 2,
  "description" : "this will direct you on home page",
  "order" : 1,
  "taxonomy" : "nav_bar"
}
{
  "_id" : 4,
  "name" : "link2",
  "slug" : "link2",
  "parent" : 2,
  "description" : "this will direct you on home page",
  "order" : 2,
  "taxonomy" : "nav-bar"
}
{
  "_id" : 5,
  "name" : "extra link",
  "slug" : "extra-link",
  "parent" : 0,
  "description" : "this will direct you on home page",
  "order" : 3,
  "taxonomy" : "nav-bar"
}
{
  "_id" : 6,
  "name" : "extra link1",
  "slug" : "extra-link1",
  "parent" : 5,
  "description" : "this will direct you on home page",
  "order" : 1,
  "taxonomy" : "nav-bar"
}
{
  "_id" : 7,
  "name" : "extra link2",
  "slug" : "extra-link2",
  "parent" : 5,
  "description" : "this will direct you on home page",
  "order" : 2,
  "taxonomy" : "nav-bar"
}

我将如何根据 parent 字段和 order 字段使用 golang 检索这些数据,它们按排序顺序排列,并且还遵循子父层次结构。现在,我只是使用 db.collectionname.find().pretty() 检索所有数据。但现在我必须按订单字段以及父子层次结构对其进行排序。

我在 mongodb shell 中尝试了以下查询:-

db.CollectionName.find().pretty()

它将向我显示完整的数据。但我需要例如记录第一个具有 _id:1、parent:0、order:1 然后它将显示在顶部并记录第二个具有 _id:2、parent:0、order:2 它将显示在第二个、第三个记录中它将具有 _id:3、parent:2、order:1 然后它将显示在第二个记录的后面,因为它的父级是 _id:2 顺序第一。


解决方案


我希望我理解你的问题。

我认为您正在尝试执行以下操作。

  • 从 mongo 获取一些数据(你似乎已经涵盖了)
  • 将其放入 go 中进行进一步处理
  • 按父级和顺序排序

当您说“绑定数据”时,您可能指的是解组到数据结构。为此,您需要一个结构来支持您的数据。以下是从 JSON-to-Go 自动生成的建议:

type obj struct {
id          int    `json:"_id"`
name        string `json:"name"`
slug        string `json:"slug"`
parent      int    `json:"parent"`
description string `json:"description"`
order       int    `json:"order"`
taxonomy    string `json:"taxonomy"`
}

您可能想将该结构重命名为比“obj”更好的名称。

要解组获取 json 并将其设置为字符串,例如 s

创建一个数组来包含您的对象

var obj []obj

并执行以下操作:

err := json.Unmarshal([]byte(s), &obj)

之后您可以按照自己的喜好对其进行排序。

这是用于排序的 go 文档的链接。 https://golang.org/pkg/sort/

文中关于的知识介绍,希望对你的学习有所帮助!若是受益匪浅,那就动动鼠标收藏这篇《设计有效的 MongoDB 查询以获取格式正确的记录》文章吧,也可关注golang学习网公众号了解相关技术文章。

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>