【问题标题】:MongoDB - OR function with a lot of conditionsMongoDB - 具有很多条件的 OR 函数
【发布时间】:2016-01-30 18:43:14
【问题描述】:

当我在 $or 函数中使用大量条件进行 MongoDB 查询时,我遇到了一种奇怪的行为。

基本上会发生 100 个结果在 DBCursor 中瞬间循环,随后的 5000 个结果在 2 分钟后循环!

这是代码(进行查询的方法):

public Object getMongoData(String aDbName, String aCollectionName, DBObject aQueryObj, DBObject aSortObj, boolean aFindOne,
  DBObject aFieldsFilter, int aLimitStartPosition, int aLimitNumberResults, boolean aCreateIndex) throws Exception
  {
    // String aDbName MY_DB
    // String aCollectionName = MY_COLLECTION
    // DBObject aQueryObj = {"$or":[{"_id":"id1"},…,{"_id":"id5000"}]}
    // DBObject aSortObj = null
    // boolean aFindOne = false
    // DBObject aFieldsFilter = null
    // int aLimitStartPosition = 0
    // int aLimitNumberResults = 0
    // boolean aCreateIndex = false

    Object resultObj = null;
    DBObject query;
    DBObject filter;

    if (aQueryObj == null)
    {
      query = new BasicDBObject();
    }
    else
    {
      query = aQueryObj;
    }

    if (aFieldsFilter == null)
    {
      filter = new BasicDBObject();
    }
    else
    {
      filter = aFieldsFilter;
    }

    DBCollection collection = loadCollection(aDbName, aCollectionName);
    if (collection != null)
    {
      if (aFindOne)
      {
        resultObj = collection.findOne(query, filter);
      }
      else
      {
        if ((aSortObj != null) && !aSortObj.keySet().isEmpty())
        {
          if (aCreateIndex)
          {
            collection.createIndex(aSortObj);
          }

          resultObj = collection.find(query, filter).skip(aLimitStartPosition).limit(aLimitNumberResults).sort(aSortObj);
        }
        else
        {
          resultObj = collection.find(query, filter).skip(aLimitStartPosition).limit(aLimitNumberResults);
        }
      }
    }

    return resultObj;
  }

代码(调用前一个方法并循环结果的代码):

dbCursor = (DBCursor) getMongoData(super.getMainDatabaseName(), aCollectionName, aQueryObj, aSortObj, false, aFilterObj);
      if (dbCursor != null)
      {
        int i = 0;

        while (dbCursor.hasNext())
        {
          DBObject dbObject = dbCursor.next();

          logger.debug("SEARCH FINISHED COUNT: " + dbCursor.count() + "\t CURRENT: " + i);
          i++;
        }
      }

知道为什么会这样吗?

谢谢

【问题讨论】:

  • 你需要在这里展示一些代码,让每个人都了解你在做什么,并解释你想要实现的目标。如果您正确地解释了您需要从源数据中获得什么最终结果的问题,那么这里的人们可能会提出更好的方法。没有代码,所以场景,对你没有帮助。
  • 很公平,这是代码

标签: java mongodb mongodb-query


【解决方案1】:

由于$or函数只查询一个参数(_id),我开始使用$in,问题解决了

https://docs.mongodb.org/manual/reference/operator/query/in/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-02
    • 2020-05-22
    • 2017-03-10
    • 1970-01-01
    • 1970-01-01
    • 2023-02-04
    相关资源
    最近更新 更多