簡體   English   中英

如何查詢 MongoDB 以返回 Document 但不是所有子文檔?

[英]How to query MongoDB to return Document but not all subdocuments?

假設我有一個這樣的文件:


      {
         _id: ObjectId("1234567890"),
         author: "ABC1",
         text:"this is a Post",
         details: {
            time: "14/05/2015",
            Edit: "none"
         },
         comments: [
             { 
                   comment_text: "Hello",
                    user: "alan",
                      time:"20/05/2014 20:44" 
               }, 
             { 
                    comment_text: "Hi Every One",
                     user: "bob",
                      time:"20/05/2014 20:44"
              },
             { 
                     comment_text: "Good morning , Alan", 
                     user: "Alan",
                     time:"20/05/2014 20:44"
               },
             { 
                        comment_text: "I'm bob",
                        user: "bob", 
                        time:"20/05/2014 20:44"
                },
                  ],
         category: "IT"
       }

我想構建一個返回此對象的查詢,但在 comments 數組中只有 Bob 的評論。


      {
         author: "ABC1",
         text:"this is a Post",
         details: {
            time: "14/05/2015",
            Edit: "none"
         },
         comments: [
             { 
                    comment_text: "Hi Every One",
                     user: "bob",
                      time:"20/05/2014 20:44"
              },
             { 
                        comment_text: "I'm bob",
                        user: "bob", 
                        time:"20/05/2014 20:44"
                },
                  ],
         category: "IT"
       }

如何才能做到這一點?

  • 在聚合管道中使用$unwind (和$match )將使我獲得正確的子文檔,但不會作為原始文檔中的對象數組。
  • 在投影中使用$elemMatch (使用find()findOne() )只返回第一個匹配的注釋(子文檔)。

您可以在聚合管道的$project階段使用$filter運算符:

db.collection.aggregate([
  {
    $project: {
      _id: 0,
      author: 1,
      text: 1,
      details: 1,
      category: 1,
      comments: {
        $filter: {
          input: "$comments",
          as: "comment",
          cond: {
            $eq: [
              "$$comment.user",
              "bob"
            ]
          }
        }
      }
    }
  }
])

示例 mongoplayground

暫無
暫無

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

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