如何在MongoDB中的findOne之后只显示部分数组?

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

Restaurants 是一个集合,具有如下对象:

{
    _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

这个 returns 餐厅集合中的整个对象,如果我只想显示其 ID 在 get(reviewID)

中提供的评论,我该怎么办

输出:

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

这可能不是您问题的正确答案,但您可以尝试这样的答案。

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

查询

  • ObjectId("61736a0f65b9931b9e428789") 替换为 reviewId
  • 这将 return 与数组 _id 匹配的评论
  • 如果你只想得到第一个,以防总是max 1 您可以将最后一个项目替换为 {"$project": {"_id": 0, "review": {"$arrayElemAt": ["$reviews", 0]}}}

*不确定这是否是您需要的

Test code here

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

使用投影,将字段指定为 return

以下return仅是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
}

Test Here

You can also use find instead of fineOne