mongoose 查找mongodb文档,其中数组字段具有数组项,其中存在子字段

wixjitnu  于 2022-11-13  发布在  Go
关注(0)|答案(1)|浏览(148)

假设我有一个模式VideoPostsVideoPosts有一个数组字段comment

[
  {
    "user": "1",
    "post": "1",
    "comment": [
      {
        from: "Gene",
        message: "Awesome!"
      },
      {
        from: "Dash",
        message: "Great job!",
        imageAttachment: "www.image.com/imageurl"
      }
    ]
  },
  {
    "user": "1",
    "post": "2",
    "comment": [
      {
        from: "Bill",
        message: "Good video tutorial!"
      }
    ]
  },
  {
    "user": "2",
    "post": "3",
    "comment": [
      {
        from: "Bill",
        message: "This video helped me!"
      }
    ]
  },
  {
    "user": "3",
    "post": "4",
    "comment": [
      {
        from: "Bill",
        message: "I ran into this error:",
        imageAttachment: "www.image.com/imageurl"
      }
    ]
  }
]

我想找到VideoPost,其中至少有一条评论带有imageAttachment。在上面的例子中,这意味着post 1和post 4。我想使用aggregate,因为我打算将它与一些其他过滤器结合起来。
我试过了,但是没有用

db.collection.aggregate([
  {
    $match: {
      "comments.imageAttachment": {
        "$exists": true
      },
      
    },
    
  },
  
])

playground

nkoocmlb

nkoocmlb1#

这似乎只是一个打字错误,您是否尝试过使用单数形式的注解进行相同的查询?

db.collection.aggregate([
  {
    $match: {
      "comment.imageAttachment": {
        "$exists": true
      },
      
    },
    
  },
  
])

相关问题