簡體   English   中英

如何在 MongoDB 中的 findOne 之后僅顯示數組的一部分?

[英]How do I display only part of the array after findOne in MongoDB?

餐廳是一個集合,具有如下對象:

{
    _id: new ObjectId("61723c7378b6d3a5a02d908e"),
    name: 'The Blue Hotel',
    location: 'Noon city, New York',
    phoneNumber: '122-536-7890',
    website: 'http://www.bluehotel.com',
    priceRange: '$$$',
    cuisines: [ 'Mexican', 'Italian' ],
    overallRating: 0,
    serviceOptions: { dineIn: true, takeOut: true, delivery: true },
    reviews: [
      {
        _id: new ObjectId("61736a0f65b9931b9e428789"),
        title: 'asd',
        reviewer: 'khoh',
        rating: 3,
        dateOfReview: '5/12/2002',
        review: 'hey'
      },
        _id: new ObjectId("61736a0f65b9931b9e428790"),
        title: 'dom',
        reviewer: 'firuu',
        rating: 4,
        dateOfReview: '25/1/2002',
        review: ' bruh'
      }
    ]
  }

我正在使用以下代碼根據提供的評論 ID 查找此對象

async get(reviewId) {

    const restaurantsCollection = await restaurants();
    reviewId = ObjectId(reviewId)
    const r = await restaurantsCollection.findOne({reviews: {$elemMatch: {_id: reviewId}}})
    return r

這將返回餐廳集合中的整個對象,如果我只想顯示其 ID 在 get(reviewID) 中提供的評論,我該怎么辦

輸出:

{
  _id: new ObjectId("61736a0f65b9931b9e428790"),
   title: 'dom',
   reviewer: 'firuu',
   rating: 4,
   dateOfReview: '25/1/2002',
   review: ' bruh'
}

使用投影,指定要返回的字段

以下僅返回在 get(reviewID) 中提供 id 的評論

async get(reviewId) {
  const restaurantsCollection = await restaurants();
  reviewId = ObjectId(reviewId)

  const r = await restaurantsCollection.findOne(
    { reviews: { $elemMatch: { _id: reviewId } } },
    { "reviews.$": 1 }
  )

  return r
}

在這里測試

您也可以使用 find 而不是 FineOne

詢問

  • ObjectId("61736a0f65b9931b9e428789")替換為reviewId
  • 這將返回與數組中的_id匹配的評論
  • 如果你只想得到第一個,如果總是最多 1 你可以用{"$project": {"_id": 0, "review": {"$arrayElemAt": ["$reviews", 0]}}}

*不確定這是否是您需要的

測試代碼在這里

aggregate(
[{"$match": {"reviews._id": ObjectId("61736a0f65b9931b9e428789")}}
 {"$set": 
   {"reviews": 
     {"$filter": 
       {"input": "$reviews",
        "cond": 
        {"$eq": ["$$this._id", ObjectId("61736a0f65b9931b9e428789")]}}}}},
  {"$project": {"_id": 0, "reviews": 1}}])

這可能不是您問題的正確答案,但您可以嘗試這樣的操作。

const r = await restaurantsCollection.findOne({reviews: {$elemMatch: {_id: reviewId}}})?.reviews.find(review => review._id.equals(reviewId))

暫無
暫無

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

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