从X量的时间和user_id获取记录

时间:2016-12-26 21:55:01

标签: mongodb

所以我在Mongo中有以下集合结构:

{
     "comments" : [ 
        {
            "user_id" : 1,
            "full_name" : "Lin-Manuel Miranda",
            "comment" : "Comment 1",
            "posted" : ISODate("2016-09-14T17:23:45.000Z")
        {
            "user_id" : 3,
            "full_name" : "Frank Sinatra",
            "comment" : "Comment 2",
            "posted" : ISODate("2016-09-14T17:23:45.000Z")
        }, 
     ]
}

我正在尝试记录user_id为1并且从X时间点过来的记录,例如:

db.getCollection('modulemetas').find({
    $and: [
        {"comments.posted" : { $gt: new Date(ISODate("2016-12-26T17:09:28.000Z")-18*60000)}}, {'comments.user_id' : 1},
        {"comments.user_id" : 1}
    ]
}, {"comments.user_id" : 1})

我似乎正在收回所有记录,而我似乎无法解决这些问题。我不认为$and它在这里有所帮助,所以我认为这可能是我出错的地方......

1 个答案:

答案 0 :(得分:1)

您应该使用$ elemMatch运算符。

我玩了一些你的数据(在mongo shell中),

初始数据集

> db.modulemetas.find().pretty()
{
    "_id" : ObjectId("5861929820260f49fc374c3e"),
    "comments" : [
        {
            "user_id" : 1,
            "full_name" : "Lin-Manuel Miranda",
            "comment" : "Comment 1",
            "posted" : ISODate("2016-09-14T17:23:45Z")
        },
        {
            "user_id" : 3,
            "full_name" : "Frank Sinatra",
            "comment" : "Comment 2",
            "posted" : ISODate("2016-09-14T17:23:45Z")
        }
    ]
}
{
    "_id" : ObjectId("5861936320260f49fc374c3f"),
    "comments" : [
        {
            "user_id" : 1,
            "full_name" : "Lin-Manuel Miranda",
            "comment" : "Comment 1",
            "posted" : ISODate("2016-09-14T17:23:45Z")
        },
        {
            "user_id" : 3,
            "full_name" : "Frank Sinatra",
            "comment" : "Comment 2",
            "posted" : ISODate("2016-12-27T17:23:45Z")
        }
    ]
}
{
    "_id" : ObjectId("586193d320260f49fc374c40"),
    "comments" : [
        {
            "user_id" : 1,
            "full_name" : "Lin-Manuel Miranda",
            "comment" : "Comment 1",
            "posted" : ISODate("2016-12-28T17:23:45Z")
        },
        {
            "user_id" : 3,
            "full_name" : "Frank Sinatra",
            "comment" : "Comment 2",
            "posted" : ISODate("2016-12-27T17:23:45Z")
        }
    ]
}

您正在寻找的查询(您只需将其翻译为您的驱动程序语言):

> db.modulemetas.find({comments:{$elemMatch:{posted:{ $gt: new Date(ISODate("2016-12-26T17:09:28.000Z")-18*60000)},user_id : 1}}}, {"comments.user_id" : 1}).pretty()

答案:

{
    "_id" : ObjectId("586193d320260f49fc374c40"),
    "comments" : [
        {
            "user_id" : 1
        },
        {
            "user_id" : 3
        }
    ]
}

对象_id" 586193d320260f49fc374c40"是唯一一个文档具有user_id 1注释的文档,它是在定义日期之后发布的。

这是mongodb文档链接

https://docs.mongodb.com/v3.2/reference/operator/query/elemMatch/