0

假设我在 Mongo 中有以下数据:

{
    "id": "foo1",
    "description": "myFoo1",
    "bars": [
        {
            "id": "foo1bar1",
            "description": "myFoo1Bar1",
            "builton": "2010-03-01T05:00:00.000Z"
        },
        {
            "id": "foo1bar2",
            "description": "myFoo1Bar2",
            "builton": "2011-03-01T05:00:00.000Z"
        }
    ]
}
{
    "id": "foo2",
    "description": "myFoo2",
    "bars": [
        {
            "id": "foo2bar1",
            "description": "myFoo2Bar1",
            "builton": "2012-03-01T05:00:00.000Z"
        },
        {
            "id": "foo2bar2",
            "description": "myFoo2Bar2",
            "builton": "2013-03-01T05:00:00.000Z"
        }
    ]
}

我的问题是双重的,我想:

是否可以执行一个查询,该查询只返回bar日期在指定范围内的文档,并且只返回该bars日期范围内的文档?例如,如果我的日期范围是 2010-02-01 到 2010-04-01,这就是我想要返回的内容:

{
    "id": "foo1",
    "description": "myFoo1",
    "bars": [
        {
            "id": "foo1bar1",
            "description": "myFoo1Bar1",
            "builton": "2010-03-01T05:00:00.000Z"
        }
    ]
}

这是构建数据的最佳方式还是我应该更多地进行相关操作(即有两个单独的文档(foosbars),然后只有一个fooId字段bar)?

4

1 回答 1

1

通常,您将始终获得完整的文档。如果您真的只想要子数组的一个元素,那么您最好的选择是将每个“条”拆分为它自己的文档。在这种情况下,最好像在 RDBM 中那样使用两个集合,但可以只存储如下内容:

{
    "foo" : {
        "id": "foo1",
        "description": "myFoo1",
    }
    "id": "foo1bar1",
    "description": "myFoo1Bar1",
    "builton": "2010-03-01T05:00:00.000Z"
},
{
    "foo" : {
        "id": "foo1",
        "description": "myFoo1",
    }
    "id": "foo1bar2",
    "description": "myFoo1Bar2",
    "builton": "2011-03-01T05:00:00.000Z"
}

即,用每个条存储“foo”信息。

于 2013-07-24T10:37:28.540 回答