代码之家  ›  专栏  ›  技术社区  ›  Diego Gallegos

将文档数组显示为id为键的对象

  •  0
  • Diego Gallegos  · 技术社区  · 7 年前

    有没有办法使用 project 或 group 在mongo中,是否要将一系列文档或子文档转换为一个对象,其中documents ObjectId为键,document/subdocument为值?

    例如:

    const book = Schema({
        name: {type: String},
        authors: [{type: mongoose.Schema.Types.ObjectId, ref: 'Author'}]
    })
    
    const author = Schema({name: {type: String}})
    

    如果查询所有书籍:

    Book.find({}).populate('authors').lean().exec()

    然后你会得到:

    [{
        id: 10,
        name: 'Book 1',
        authors: [{
            id: 1, 
            name: 'Author1'
        }]
    
    },...]
    

    但我想要这个:

    [{
        id: 10,    
        name: 'Book 1',
        authors: {
            1: {id: 1, name: 'Author 1'}
        }
    },...]
    

    我知道在从mongo查询之后迭代对象可以做到这一点,但我想在mongo上运行查询更有效。

    0 回复  |  直到 7 年前
        1
  •  1
  •   Neil Lunn    7 年前

    这里主要考虑的是你想要的“钥匙”实际上是 ObjectId 值,而不是真正的“字符串”,这实际上是JavaScript对象的一个要求,因为所有“键” 必须 成为一根“绳子”。对于JavaScript来说,这并不是什么大问题,因为JavScript将“stringify”任何指定为“key”的参数,但是 重要吗 对于BSON来说,MongoDB实际上就是这样 “说话”

    所以你可以用MongoDB实现这一点,但你需要MongoDB 4。至少是为了支持 $convert 聚合运算符或它的 捷径 方法 $toString .这也意味着 populate() 实际上,你使用的是MongoDB $lookup :

    let results = await Books.aggregate([
      { "$lookup": {
        "from": Author.collection.name,
        "localField": "authors",
        "foreignField": "_id",
        "as": "authors"
      }},
      { "$addFields": {
        "authors": {
          "$arrayToObject": {
             "$map": {
               "input": "$authors",
               "in": { "k": { "$toString": "$$this._id" }, "v": "$$this" }
             }
           }
         }
      }}
    ])
    

    或者,如果您更喜欢其他语法:

    let results = await Books.aggregate([
      { "$lookup": {
        "from": "authors",
        "let": { "authors": "$authors" },
        "pipeline": [
          { "$match": { "$expr": { "$in": [ "$_id", "$$authors" ] } } },
          { "$project": {
            "_id": 0,
            "k": { "$toString": "$_id" },
            "v": "$$ROOT"
          }}
        ],
        "as": "authors"
      }},
      { "$addFields": {
        "authors": { "$arrayToObject": "$authors" }
      }}
    ])
    

    这将返回类似于:

    {
            "_id" : ObjectId("5c7f046a7cefb8bff9304af8"),
            "name" : "Book 1",
            "authors" : {
                    "5c7f042e7cefb8bff9304af7" : {
                            "_id" : ObjectId("5c7f042e7cefb8bff9304af7"),
                            "name" : "Author 1"
                    }
            }
    }
    

    所以 $arrayToObject 实际的“对象”是否会输出一个对象数组 k 和 v 对应于 钥匙 和 价值 .但是 必须 在中有一个有效的“字符串” "k" 这就是为什么你 $map 首先对数组内容进行重新格式化。

    或者作为 候补 ,你可以 $project 在 pipeline 争论 $lookup 而不是使用 $map 后来也发生了同样的事情。

    具有 客户端 JavaScript,翻译是一个类似的过程:

    let results = await Books.aggregate([
      { "$lookup": {
        "from": Author.collection.name,
        "localField": "authors",
        "foreignField": "_id",
        "as": "authors"
      }},
      /*
      { "$addFields": {
        "authors": {
          "$arrayToObject": {
             "$map": {
               "input": "$authors",
               "in": { "k": { "$toString": "$$this._id" }, "v": "$$this" }
             }
           }
         }
      }}
      */
    ])
    
    results = results.map(({ authors, ...rest }) => 
      ({
        ...rest, 
        "authors": d.authors.reduce((o,e) => ({ ...o, [e._id.valueOf()]: e }),{})
      })
     )
    

    或者 填充()

    let results = await Book.find({}).populate("authors");
    results = results.map(({ authors, ...rest }) => 
      ({
        ...rest, 
        "authors": (!authors) ? {} : authors.reduce((o,e) => ({ ...o, [e._id.toString()]: e }),{})
      })
     )
    

    笔记 然而 填充() 和 $lookup 真的很不一样。MongoDB $lookup 是一个 单一请求 到返回的服务器 一个回答 .使用 填充() 实际上调用 多个查询 “加入”了吗 客户端JavaScript代码 即使它对你隐瞒了它在做什么。

    推荐文章