首页 > 解决方案 > 如何在 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)
                        }
                    })
                })

该代码没有错误,也没有警告。

标签: node.jsmongodbmongoose

解决方案


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);
      }
    })
  });  

推荐阅读