簡體   English   中英

MongoDB:使用嵌套數組過濾的find和findOne

[英]MongoDB: find and findOne with nested array filtering

事實證明,這項小任務比我想象的要難。

考慮以下非常簡單的帖子集合。 假設我要顯示所有帖子,並僅顯示未刪除的評論。

IE會從comments數組中過濾出已刪除的評論。

由於每個帖子我有100條已刪除的評論,有沒有辦法在服務器端執行此操作?

集合:

{
  "author": {},
  "message": "This is post1",
  "comments": [
    {
      "message": "Im number 1!!!",
      "state": {
        "deleted": false
      }
    },
    {
      "message": "YOU MOTHERF****R",
      "state": {
        "deleted": true
      }
    },
    {
      "message": "tHIS IS GREAT!",
      "state": {
        "deleted": false
      }
    },
    {
      "message": "I can type better than you guys",
      "state": {
        "deleted": false
      }
    }
  ]
},
{
  "author": {},
  "message": "This is post 2",
  "comments": [
    {
      "message": "This is bulls**t",
      "state": {
        "deleted": true
      }
    },
    {
      "message": "YOU MOTHERF****R",
      "state": {
        "deleted": true
      }
    },
    {
      "message": "I hate u!",
      "state": {
        "deleted": true
      }
    },
    {
      "message": "I wanna have your children",
      "state": {
        "deleted": false
      }
    }
  ]
}

我將TL; DR,因為事實證明這真是太難了。 我試過$elemMatch ,我試過$redact (也$$當前和$$ ROOT),我試過$map ,我已經試過了聚合框架,我試過$project

您可以在這里閱讀所有內容: https : //www.devsbedevin.net/mongodb-find-findone-with-nested-array-filtering-finally/

TL; DR

解決方案似乎是使用聚合框架來過濾數組並使用結果覆蓋comments屬性。 這比聽起來簡單:

db.getCollection('posts').aggregate(
    {$match: {"author.id": authorId}},
    {$addFields : {"comments":{$filter:{ // We override the existing field!
        input: "$comments",
        as: "comment",
        cond: {$eq: ["$$comment.state.deleted", false]}
    }}}}
);

結果:

{
  "author": {},
  "message": "This is post1",
  "comments": [
    {
      "message": "Im number 1!!!",
      "state": {
        "deleted": false
      }
    },
    {
      "message": "tHIS IS GREAT!",
      "state": {
        "deleted": false
      }
    },
    {
      "message": "I can type better than you guys",
      "state": {
        "deleted": false
      }
    }
  ]
},
{
  "author": {},
  "message": "This is post 2",
  "comments": [
    {
      "message": "I wanna have your children",
      "state": {
        "deleted": false
      }
    }
  ]
}

暫無
暫無

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

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