【问题标题】:Querying the most recent posts in a MongoDB collection查询 MongoDB 集合中的最新帖子
【发布时间】:2019-06-13 22:36:54
【问题描述】:

对 Mongodb/Mongoose/Node 来说相当新。尝试进行查询以检索集合中所有文档的最新帖子(例如 10 个最新帖子)。

我尝试了几种不同的查询方式。

MessageboardModel.find({"posts": {"time": {"$gte": ISODate("2014-07-02T00:00:00Z")}}} ...

我尝试执行上述操作只是为了尝试获取正确的嵌套时间属性,但我尝试的所有操作都会引发错误。我肯定在这里遗漏了一些东西......

这是集合中的示例文档:

{
    "_id": {
        "$oid": "5c435d493dcf9281500cd177"
    },
    "movie": 433249,
    "posts": [
        {
            "replies": [],
            "_id": {
                "$oid": "5c435d493dcf9281500cd142"
            },
            "username": "Username1",
            "time": {
                "$date": "2019-01-19T17:24:25.204Z"
            },
            "post": "This is a post title",
            "content": "Content here."
        },
        {
            "replies": [],
            "_id": {
                "$oid": "5c435d493dcf9281500cd123"
            },
            "username": "Username2",
            "time": {
                "$date": "2019-01-12T17:24:25.204Z"
            },
            "post": "This is another post made earlier",
            "content": "Content here."
        }
    ],
    "__v": 0
}

集合中有许多文档。我想在整个集合中的所有文档中获取最近的 10 个帖子。

有什么帮助吗?

【问题讨论】:

  • 您可以使用 .dot 表示法。 MessageboardModel.find({"posts.time": {"$gte": ISODate("2014-07-02T00:00:00Z")}})
  • 您应该考虑将帖子移动到单独的集合中,而不是将它们嵌入到父对象中。如果您要查询单独的帖子,此更改可能对您有益。

标签: mongodb mongoose


【解决方案1】:

您可以尝试使用aggregation查询:

步骤: 1> 匹配特定文档

2> 使用$unwind 拉伸其数组的文档。

3> 使用来自poststime 字段进行排序。

4> 如果需要显示特定字段,请选择字段。

5>添加限制,你想要多少个文档。

<YOUR_MODEL>.aggregate([
{$match:{
"movie": 433249 //you may add find conditions here, otherwise you can keep {} or remove $match from here
}},
{$unwind:"$posts"}, //this will make the each array element with different different docs.
{$sort:{"posts. time":1}}, // sort using the date field now, depends on your requirement use -1 /1
{$project:{posts:1}}, //select docs only from posts field. [u can remove if you want every element, or may modify]
{$limit:10} //you want only last 10 posts
]).exec();

如果您仍有任何问题或遇到任何错误,请告诉我。

很想回答。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-31
    相关资源
    最近更新 更多