如何使用mongodb查询将数据库中的元素与同一集合中存储的数组中的另一个元素进行比较

时间:2019-10-09 16:41:27

标签: mongodb mongodb-query

这是我的问题。

这是我的样本记录

{
    "_id" : ObjectId("5d9b69fae4757402b4b4ca0d"), 
    "status_changed_utc" : [
        {
            "status" : NumberInt(1), 
            "time" : ISODate("2019-05-20T23:03:10.000+0000")
        }, 
        {
            "status" : NumberInt(2), 
            "time" : ISODate("2019-05-23T23:04:03.000+0000")
        }, 
        {
            "status" : NumberInt(4), 
            "time" : ISODate("2019-05-23T23:05:06.000+0000")
        }, 
        {
            "status" : NumberInt(5), 
            "time" : ISODate("2019-05-23T23:05:07.000+0000")
        }, 
        {
            "status" : NumberInt(6), 
            "time" : ISODate("2019-05-23T23:05:09.000+0000")
        }
    ], 
    "requested_completion_utc" : ISODate("2019-05-22T23:05:09.000+0000")
},
{
    "_id" : ObjectId("5d9b69fae4757402b4b4ca1e"), 
    "status_changed_utc" : [
        {
            "status" : NumberInt(1), 
            "time" : ISODate("2019-06-20T23:03:10.000+0000")
        }, 
        {
            "status" : NumberInt(2), 
            "time" : ISODate("2019-07-23T23:04:03.000+0000")
        }, 
        {
            "status" : NumberInt(4), 
            "time" : ISODate("2019-07-23T23:05:06.000+0000")
        }, 
        {
            "status" : NumberInt(5), 
            "time" : ISODate("2019-05-23T23:05:07.000+0000")
        }, 
        {
            "status" : NumberInt(6), 
            "time" : ISODate("2019-07-23T23:05:09.000+0000")
        }
    ], 
    "requested_completion_utc" : ISODate("2019-08-22T23:05:09.000+0000")
},

当“ status_changed_utc.status”为NumberInt(2)时,我希望找出记录,其中“ requested_completion_utc”字段的日期大于“ status_changed_utc”字段中的日期。

在此示例中,我希望获得第二条记录。

除了$ unwind函数外,还有其他方法可以解决此问题吗?

谢谢

3 个答案:

答案 0 :(得分:0)

如果NumberInt(2)始终位于数组的第二个位置。这应该很容易。

db.whatever.find({ $expr: { $gt: [ "$requested_completion_utc" , "$status_changed_utc.1" ] } })

答案 1 :(得分:0)

要求是找到符合以下标准的记录,如何在不使用展开的情况下写查询?

requested_completion_utc> status_changed_utc.time和status_changed_utc.status = 2,其中status_changed_utc.time来自具有status_changed_utc.status = 2的记录

答案 2 :(得分:0)

最终,我们找到了答案。

numpy.where(input == i)