簡體   English   中英

如何獲取與mongoose中查詢相同索引的數組元素

[英]How to get an array element in the same index as the query in mongoose

我有以下架構:

const PublicationSchema = mongoose.Schema({
    title: {
        type: String,
        required: true
    },
    files:[{ 
        contentType: String, 
        data: Buffer,
        name: String
    }]

})

我想要做的是獲取與查詢具有相同索引的文件。例如,我有這個 object:

  _id: new ObjectId("637f20ce6ce5c48d9788a1ff"),
  title: 'TEST',
  files: [
    {
      contentType: 'application/pdf',
      name: 'imId1',
      _id: new ObjectId("id1")
    },
    {
      contentType: 'application/pdf',
      name: 'imId2',
      _id: new ObjectId("id2")
    }
  ]

如果我查詢 id2 它只檢索:

    {
      contentType: 'application/pdf',
      name: 'imId2',
      _id: new ObjectId("id2")
    }

我試圖使用的是const onePublication = await Publication.findOne({ "files._id": req.body.fileId},{})但這會檢索每個字段。

我打算告訴它不要使用field:0檢索其他字段,但我意識到這仍然會檢索該字段的其他索引中的文件。

有沒有辦法告訴它只檢索具有相同索引的那個,或者我應該完全使用另一個查詢?

其中一個選項是首先$unwind數組。 $match你的標准。 然后, $replaceRoot獲取您的數組條目。

db.collection.aggregate([
  {
    "$unwind": "$files"
  },
  {
    $match: {
      "files._id": "id2"
    }
  },
  {
    "$replaceRoot": {
      "newRoot": "$files"
    }
  }
])

蒙戈游樂場

如果大多數時候您打算只訪問數組對象,請考慮更改架構以將文件存儲為單獨的集合。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM