我在 RethinkDB 中有一个表格,我想要检索未设置字段single
的所有记录。由于没有强制模式,因此存储的某些文档不遵循完全相同的结构。
表中的示例数据:
{
"id": "1",
"age": 27,
"sex": "female",
"single": true
},
{
"id": "2",
"sex": "female",
"age": 40
},
{
"id": "3",
"age": 45,
"sex": "male",
"single": false
},
{
"id": "4",
"sex": "male",
"age": 16
}
我需要编写一个 ReQL 查询来检索记录2和4.任何帮助都将非常感谢。
答案 0 :(得分:4)
这是您在没有字段single
或字段single
为null
的情况下检索所有文档的方法。
r.table('data').filter(function(doc) {
return doc.hasFields('single').not();
}).run().then(...).error(...)
如果您只想要未定义的字段:
r.table('data').filter(function(doc) {
return doc('single').ne(null);
}).run().then(...).error(...)
这样做是因为如果single
不是键,则会在过滤器中返回错误,并且会跳过该文档。
文档:
hasFields
:http://www.rethinkdb.com/api/javascript/has_fields/ filter
:http://www.rethinkdb.com/api/javascript/filter/ 如果你有很多数据,你也可能想要使用索引。
答案 1 :(得分:-1)
尝试这样的事情
var data = [{
"id": "1",
"age": 27,
"sex": "female",
"single": true
},
{
"id": "2",
"sex": "female",
"age": 40
},
{
"id": "3",
"age": 45,
"sex": "male",
"single": false
},
{
"id": "4",
"sex": "male",
"age": 16
}];
var filtered = data.filter(function(elem){return typeof(elem.single) !== 'undefined';}));
答案 2 :(得分:-1)
如果你想要一个本机解决方案,这里有一个简单的非索引示例:
var result = [];
original.forEach(value) {
if(value.single != null) {
result.push(value);
}
}
对于mongodb,您可以在此处阅读有关查询和预测的内容:http://docs.mongodb.org/manual/reference/operator/query/