从MongoDB集合的文档中获取满足条件的元素?

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了从MongoDB集合的文档中获取满足条件的元素?相关的知识,希望对你有一定的参考价值。

如果我在这样的集合中有一些文档:

db.test.find()
[
    author_id: 1
    reviews: [article_id: 1, score: 10, ...,
              article_id: 2, score: 7, ...,
              article_id: 3, score_9, ...
              ...
             ]
,

    author_id: 2
    reviews: [article_id: 2, score: 8, ...,
              article_id:4, score: 3, ...
              ...
             ]
,
...
]

如何获得包含满足标准的所有评论的列表,例如。 article_id等于2,就像:

[article_id: 2, author_id: 1, score: 7,
article_id: 2, author_id: 2, score: 8
...
]

我是MongoDB的新手^ _ ^。

答案

您可以在mongo 3.6版中使用以下聚合。

$filter$arrayElemAt输出匹配的评论,然后$mergeObjects将匹配的评论文档与author_id结合起来。

$replaceRoot将合并文件推广到顶级水平。

db.col.aggregate(
  "$replaceRoot":
    "newRoot":
      "$mergeObjects":[
        "author_id":"$author_id",
        "$arrayElemAt":[
          "$filter":
            "input":"$reviews",
            "as":"rv",
            "cond":"$eq":["$$rv.article_id",2]
          ,
        0]
      ]
    
  
)

以上是关于从MongoDB集合的文档中获取满足条件的元素?的主要内容,如果未能解决你的问题,请参考以下文章