node.js - node mongodb 3.4 使用带有指定字段的 find 和 toArray 不过滤结果
问题描述
同样,使用 mongo v3.4 并引用这些文档:https ://docs.mongodb.com/v3.4/tutorial/project-fields-from-query-results/
我的示例如下所示:
const m = this.getCollection(SOME_COLLECTION);
m.find({
'_id': {
$nin: [Ace, Bay],
},
'value.someCategory': {
$type: 'object',
},
}, {
'_id': 0,
'value.someCategory': 1,
}).toArray((err, doc) => {
if (err) {
console.log(err);
} else {
console.log(doc);
}
});
我的doc
数组将返回遵循我value.someCategory
的对象类型过滤器的所有项目,但不会删除_id
并且将返回所有字段,即使我只想指定value.someCategory
字段。
mongo 中的示例数据:
[
{
_id: 'hello',
value: {
someCategory: [Object],
name: 'hello',
otherCategory: true,
}
},
{
_id: 'Ace',
value: {
someCategory: [Object],
name: 'Ace',
otherCategory: true,
}
},
{
_id: 'testing',
value: {
someCategory: null,
name: 'testing',
otherCategory: true,
}
},
]
并期望结果是:
[
{
someCategory: [Object],
},
]
根据上面链接的文档,指定的字段应该是第二个参数。我现在想知道使用是否toArray
会影响返回值?
解决方案
改用.project
游标方法
db.collection('collection')
.find({ '_id': { '$nin': [Ace, Bay] }, 'value.someCategory': { '$type': 'object' }})
.project({ '_id': 0, 'value.someCategory': 1 })
.toArray()
推荐阅读
- ios - 在用户交互后保持多个 AVAudioPlayer 同步
- r - 按列对表列表应用函数
- javascript - 在主节点文件中使用 modules.exports
- angular - Angular 通用:找不到或无法读取要导入的文件:~src/main.scss
- multithreading - Goroutines (cgo):使用 goroutines 时产生无法解释的 OS 线程
- python - 为什么 List 不能包含多种类型?
- symfony - Symfony 4 - 服务注入只能在没有缓存的情况下工作
- apache - Solr SimplePostTool 使用混乱
- c++ - 即使从未实例化引用变量主模板,是否也需要对其进行初始化?
- javascript - 不要在循环中创建函数 no-loop-func Axios 请求异步等待