代码之家  ›  专栏  ›  技术社区  ›  mandaputtra

如何查找MongoDB中有特定字段的集合?

  •  0
  • mandaputtra  · 技术社区  · 7 年前

    我想搜索一些在MongoDB中有特定字段的集合。假设有两个集合 名称 而另一个不是。

    虽然我发现有人问我 this ,现在答案过时了。现在的蒙古斯版本怎么办?

    这里是我尝试的代码,我成功地获得了所有集合的名称,但是当我搜索特定的字段时,它不起作用,没有给我任何错误。

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

    该代码上没有错误和警告。

    1 回复  |  直到 7 年前
        1
  •  0
  •   num8er    7 年前

    mongoose.connection 返回本地MongoDB连接,您使用该连接执行的所有操作 db. 前缀和直接在MongoDB控制台上执行的相同。

    所以在使用本机连接描述符时,不要等待Mongoose执行相同的操作。

    当您以本地方式处理集合时,您必须理解 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);
          }
        })
      });