假设我在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"
}
]
}
这是构建数据的最佳方式吗?还是我应该更加关联(即有两个单独的文档(foos
和bars
)然后只有一个fooId
字段bar
)?
答案 0 :(得分:1)
通常,您将始终获得完整的文档。如果你真的只想要一个子数组的一个元素,那么你最好的选择是将每个“bar”分成它自己的文档。在这种情况下,使用两个集合可能会更好,就像你在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”信息。