MongoDB,使用聚合操作从文档中返回选定的字段。

huangapple go评论58阅读模式
英文:

MongoDB, return selected fields from document with aggregation operations

问题

根据您提供的信息,您想要重新编写查询,以便在每个返回的评论中包含productId。以下是重写的查询:

db.comments.aggregate([
  {
    $match: {
      "comments._id": {
        $in: [
          ObjectId('630b7868f51e10876223b4aa'),
          ObjectId('630bd277f919a9e9c0e7a559')
        ]
      }
    }
  },
  {
    $unwind: "$comments"
  },
  {
    $match: {
      "comments._id": {
        $in: [
          ObjectId('630b7868f51e10876223b4aa'),
          ObjectId('630bd277f919a9e9c0e7a559')
        ]
      }
    }
  },
  {
    $project: {
      _id: 1,
      "comment.userId": "$comments.userId",
      "comment.userName": "$comments.userName",
      "comment.date": "$comments.date",
      "comment.confirmed": "$comments.confirmed",
      "comment.likes": "$comments.likes",
      "comment.content": "$comments.content",
      "comment._id": "$comments._id",
      "comment.usersWhoLiked": "$comments.usersWhoLiked",
      "comment.productId": "$productId" // Add productId to each comment
    }
  }
])

这个查询首先使用$match阶段筛选包含指定评论ID的文档,然后使用$unwind阶段展开comments数组,接着再次使用$match来匹配指定的评论ID。最后,使用$project阶段将所需字段包括productId添加到每个评论中。

请注意,这只是一种方式,您可以根据自己的需求进行进一步的调整和优化。

英文:

With given query I also want to return productId.

I have collection comments that contains documents with data about productId and comments for given product

Example document in this collection:

{
  "_id": {
    "$oid": "635ee64f55460d1796447662"
  },
  "productId": "63413800d36ed477adc763d0",
  "__v": 0,
  "comments": [
    {
      "userId": "",
      "userName": "test",
      "date": "2022.12.18.21.51.36",
      "confirmed": false,
      "likes": {
        "up": 0,
        "down": 0
      },
      "content": {
        "rating": 6,
        "description": "testtesttest"
      },
      "image": {
        "added": false,
        "images": []
      },
      "_id": {
        "$oid": "639f7d58b6206a863c4a7aba"
      },
      "usersWhoLiked": []
    },
    {
      "userId": "",
      "userName": "test",
      "date": "2022.12.18.21.52.19",
      "confirmed": false,
      "likes": {
        "up": 0,
        "down": 0
      },
      "content": {
        "rating": 6,
        "description": "testtesttest"
      },
      "image": {
        "added": true,
        "images": [
          "comments/63413800d36ed477adc763d0/639f7d83b6206a863c4a7ad6/dell.jpg"
        ]
      },
      "_id": {
        "$oid": "639f7d83b6206a863c4a7ad6"
      },
      "usersWhoLiked": []
    }
  ]
}

My exmaple query:

db.comments.aggregate([{$match: {"comments._id": {$in: [ObjectId('630b7868f51e10876223b4aa'), ObjectId('630bd277f919a9e9c0e7a559')]}}},
{$project: {comment: {$filter: {input: "$comments", as: "comment", cond: {$in: ["$$comment._id", [ObjectId("630b7868f51e10876223b4aa"), ObjectId("630bd277f919a9e9c0e7a559")]]}}}}}])

With this query I get the result :

{ _id: ObjectId("630b7868f51e10876223b4a6"),
  comment: 
   [ { userId: '62f29c2c324f4778dff443f6',
       userName: 'User',
       date: '2022.08.19',
       confirmed: false,
       likes: { up: 3, down: 0 },
       content: { rating: 4, description: 'Super laptop <3' },
       _id: ObjectId("630b7868f51e10876223b4aa"),
       usersWhoLiked: 
        [ { userId: '62f29c2c324f4778dff443f6',
            likeUp: true,
            _id: ObjectId("630d2b0494370efb37107983") },
          { userId: '6322434f2b5bbac87f0e7aba',
            likeUp: true,
            _id: ObjectId("632243702b5bbac87f0e7afa") },
          { userId: '62f2991e324f4778dff443d4',
            likeUp: true,
            _id: ObjectId("63af4d77c8991b74d6986995") } ] } ] }
{ _id: ObjectId("630bd277f919a9e9c0e7a555"),
  comment: 
   [ { userId: '62f29c2c324f4778dff443f6',
       userName: 'User',
       date: '2022.08.28',
       confirmed: false,
       likes: { up: 1, down: 1 },
       content: 
        { rating: 6,
          description: 'Laptop posiada przyjemna klawiature, nie grzeje się. Do codziennego grania wystarczy.' },
       _id: ObjectId("630bd277f919a9e9c0e7a559"),
       usersWhoLiked: 
        [ { userId: '62f29c2c324f4778dff443f6',
            likeUp: true,
            _id: ObjectId("630d2dfc94370efb37107991") },
          { userId: '62fa2549f029348f75bc9c81',
            likeUp: false,
            _id: ObjectId("631241fe755c641525dc9cfa") } ] } ] }

As you see in the result, the productId is missing.
I was trying to rebuild query with #group operator but still with out effect...
So my questsion is:
How shall I rewrite that query to get the same result but with productId in it for each returned comment

答案1

得分: 1

这是$project的工作原理,如果未指定字段,则不会输出。

所以只需在$project阶段添加productId: 1,它就会显示出来。

查看此示例

英文:

This is how $project works, if a field is not specified will not be output.

So just add productId: 1 into the $project stage and it will be shown.

Check this example.

huangapple
  • 本文由 发表于 2023年1月9日 06:46:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/75051832.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定