node.js - 如何在 mongodb 中找到具有特定字段的集合?
问题描述
我想搜索一些在 MongoDB 中具有特定字段的集合。假设有两个集合有一个名称字段,另一个没有。
使用 mongoose.js 虽然我发现有人问这个,但现在答案已经过时了。如何用现在的猫鼬版本做到这一点?
这是我尝试过的代码,我成功地获取了所有集合名称,但是当我搜索特定字段时它不起作用并且没有给我错误。
mongoose.connection.db.listCollections().toArray((error, collections) => {
collections.forEach( (collection) => {
var collectionName = mongoose.connection.db.collection(collection.name)
var count = collectionName.find({ "duck_name": { $exists: true }}).count()
if ( count > 0 ){
console.log(collection.name)
}
})
})
该代码没有错误,也没有警告。
解决方案
mongoose.connection
返回本机 mongodb 连接,您使用db.
前缀所做的一切都与您直接在 mongodb 控制台上执行的操作相同。
因此,当您使用本机连接描述符时,不要等待猫鼬的行为相同。
当您本机使用集合时,您必须了解该find
方法返回游标。
const db = mongoose.connection.db;
const collections = db.listCollections()
collections
.toArray((error, collections) => {
collections.foreach(async collection => {
const query = {"duck_name": { $exists: true }};
const count = await collection.find(query).count();
if (count === 0) return;
console.log('Found:', count, 'documents in collection:', collection.name);
const cursor = await collection.find(query);
while(await cursor.hasNext()) {
const document = await cursor.next();
console.log('document:', document._id);
}
})
});
或toArray
在光标上使用方法:
const db = mongoose.connection.db;
const collections = db.listCollections()
collections
.toArray((error, collections) => {
collections.foreach(async collection => {
const query = {"duck_name": { $exists: true }};
const count = await collection.find(query).count();
if (count === 0) return;
console.log('Found:', count, 'documents in collection:', collection.name);
const documents = await collection.find(query).toArray();
for(const document of documents) {
console.log('document:', document._id);
}
})
});
推荐阅读
- bash - 如何从 shell 上的 cURL 检索错误代码
- java - 尝试调用 getItemCount() 两次时无法访问语句
- c++ - 在少数独立功能中使用相同的对象形式类
- android - 在 RelativeLout 内将 TextView 对齐到 LinerLayout 上方
- amazon-web-services - 对 AWS 中的资源执行标记?
- python - 从时间序列数据创建正弦波(Python)
- python - 如何在测试中为多个功能重用相同的模拟
- android - Cordova 应用程序中的 YouTube iframe:“此视频不可用”
- build - 什么是构建前缀?
- uicollectionview - 从 UICollectionView 拖动时获取项目的框架