Example usage for com.mongodb QueryOperators AND

List of usage examples for com.mongodb QueryOperators AND

Introduction

In this page you can find the example usage for com.mongodb QueryOperators AND.

Prototype

String AND

To view the source code for com.mongodb QueryOperators AND.

Click Source Link

Usage

From source file:info.bunji.mongodb.synces.CollectionExtractor.java

License:Apache License

/**
 **********************************/*from w  w w .  ja  va 2  s . com*/
 *
 * @param filter
 * @param id
 * @return
 **********************************
 */
private BasicDBObject getFilterForInitialImport(BasicDBObject filter, Object id) {
    if (id == null) {
        return filter;
    }
    BasicDBObject idFilter = new BasicDBObject("_id", new BasicBSONObject(QueryOperators.GT, id));
    if (filter == null || filter.equals(new BasicDBObject())) {
        return idFilter;
    }
    return new BasicDBObject(QueryOperators.AND, ImmutableList.of(filter, idFilter));
}

From source file:org.nuxeo.ecm.core.storage.mongodb.MongoDBQueryBuilder.java

License:Apache License

protected Object pushDownNot(Object object) {
    if (!(object instanceof DBObject)) {
        throw new QueryParseException("Cannot do NOT on: " + object);
    }/*from  w  ww.  j av a 2s  .com*/
    DBObject ob = (DBObject) object;
    Set<String> keySet = ob.keySet();
    if (keySet.size() != 1) {
        throw new QueryParseException("Cannot do NOT on: " + ob);
    }
    String key = keySet.iterator().next();
    Object value = ob.get(key);
    if (!key.startsWith("$")) {
        if (value instanceof DBObject) {
            // push down inside dbobject
            return new BasicDBObject(key, pushDownNot(value));
        } else {
            // k = v -> k != v
            return new BasicDBObject(key, new BasicDBObject(QueryOperators.NE, value));
        }
    }
    if (QueryOperators.NE.equals(key)) {
        // NOT k != v -> k = v
        return value;
    }
    if (QueryOperators.NOT.equals(key)) {
        // NOT NOT v -> v
        return value;
    }
    if (QueryOperators.AND.equals(key) || QueryOperators.OR.equals(key)) {
        // boolean algebra
        // NOT (v1 AND v2) -> NOT v1 OR NOT v2
        // NOT (v1 OR v2) -> NOT v1 AND NOT v2
        String op = QueryOperators.AND.equals(key) ? QueryOperators.OR : QueryOperators.AND;
        List<Object> list = (List<Object>) value;
        for (int i = 0; i < list.size(); i++) {
            list.set(i, pushDownNot(list.get(i)));
        }
        return new BasicDBObject(op, list);
    }
    if (QueryOperators.IN.equals(key) || QueryOperators.NIN.equals(key)) {
        // boolean algebra
        // IN <-> NIN
        String op = QueryOperators.IN.equals(key) ? QueryOperators.NIN : QueryOperators.IN;
        return new BasicDBObject(op, value);
    }
    if (QueryOperators.LT.equals(key) || QueryOperators.GT.equals(key) || QueryOperators.LTE.equals(key)
            || QueryOperators.GTE.equals(key)) {
        // TODO use inverse operators?
        return new BasicDBObject(QueryOperators.NOT, ob);
    }
    throw new QueryParseException("Unknown operator for NOT: " + key);
}

From source file:org.nuxeo.ecm.core.storage.mongodb.MongoDBQueryBuilder.java

License:Apache License

protected DBObject walkAnd(List<Operand> values) {
    List<Object> list = walkOperandList(values);
    // check wildcards in the operands, extract common prefixes to use $elemMatch
    Map<String, List<FieldInfoDBObject>> propBaseKeyToDBOs = new LinkedHashMap<>();
    Map<String, String> propBaseKeyToFieldBase = new HashMap<>();
    for (Iterator<Object> it = list.iterator(); it.hasNext();) {
        Object ob = it.next();/*from w  ww .j  a  v  a 2 s .c o  m*/
        if (ob instanceof FieldInfoDBObject) {
            FieldInfoDBObject fidbo = (FieldInfoDBObject) ob;
            FieldInfo fieldInfo = fidbo.fieldInfo;
            if (fieldInfo.hasWildcard) {
                if (fieldInfo.fieldSuffix != null && fieldInfo.fieldSuffix.contains("*")) {
                    // a double wildcard of the form foo/*/bar/* is not a problem if bar is an array
                    // TODO prevent deep complex multiple wildcards
                    // throw new QueryParseException("Cannot use two wildcards: " + fieldInfo.prop);
                }
                // generate a key unique per correlation for this element match
                String wildcardNumber = fieldInfo.fieldWildcard;
                if (wildcardNumber.isEmpty()) {
                    // negative to not collide with regular correlated wildcards
                    wildcardNumber = String.valueOf(-counter.incrementAndGet());
                }
                String propBaseKey = fieldInfo.fieldPrefix + "/*" + wildcardNumber;
                // store object for this key
                List<FieldInfoDBObject> dbos = propBaseKeyToDBOs.get(propBaseKey);
                if (dbos == null) {
                    propBaseKeyToDBOs.put(propBaseKey, dbos = new LinkedList<>());
                }
                dbos.add(fidbo);
                // remember for which field base this is
                String fieldBase = fieldInfo.fieldPrefix.replace("/", ".");
                propBaseKeyToFieldBase.put(propBaseKey, fieldBase);
                // remove from list, will be re-added later through propBaseKeyToDBOs
                it.remove();
            }
        }
    }
    // generate $elemMatch items for correlated queries
    for (Entry<String, List<FieldInfoDBObject>> es : propBaseKeyToDBOs.entrySet()) {
        String propBaseKey = es.getKey();
        List<FieldInfoDBObject> fidbos = es.getValue();
        if (fidbos.size() == 1) {
            // regular uncorrelated match
            list.addAll(fidbos);
        } else {
            DBObject elemMatch = new BasicDBObject();
            for (FieldInfoDBObject fidbo : fidbos) {
                // truncate field name to just the suffix
                FieldInfo fieldInfo = fidbo.fieldInfo;
                Object value = fidbo.get(fieldInfo.queryField);
                String fieldSuffix = fieldInfo.fieldSuffix.replace("/", ".");
                if (elemMatch.containsField(fieldSuffix)) {
                    // ecm:acl/*1/principal = 'bob' AND ecm:acl/*1/principal = 'steve'
                    // cannot match
                    // TODO do better
                    value = "__NOSUCHVALUE__";
                }
                elemMatch.put(fieldSuffix, value);
            }
            String fieldBase = propBaseKeyToFieldBase.get(propBaseKey);
            BasicDBObject dbo = new BasicDBObject(fieldBase,
                    new BasicDBObject(QueryOperators.ELEM_MATCH, elemMatch));
            list.add(dbo);
        }
    }
    if (list.size() == 1) {
        return (DBObject) list.get(0);
    } else {
        return new BasicDBObject(QueryOperators.AND, list);
    }
}

From source file:org.nuxeo.ecm.core.storage.mongodb.MongoDBQueryBuilder.java

License:Apache License

/**
 * Matches the mixin types against a list of values.
 * <p>//from   w w w .j av  a 2s.co m
 * Used for:
 * <ul>
 * <li>ecm:mixinTypes = 'Foo'
 * <li>ecm:mixinTypes != 'Foo'
 * <li>ecm:mixinTypes IN ('Foo', 'Bar')
 * <li>ecm:mixinTypes NOT IN ('Foo', 'Bar')
 * </ul>
 * <p>
 * ecm:mixinTypes IN ('Foo', 'Bar')
 *
 * <pre>
 * { "$or" : [ { "ecm:primaryType" : { "$in" : [ ... types with Foo or Bar ...]}} ,
 *             { "ecm:mixinTypes" : { "$in" : [ "Foo" , "Bar]}}]}
 * </pre>
 *
 * ecm:mixinTypes NOT IN ('Foo', 'Bar')
 * <p>
 *
 * <pre>
 * { "$and" : [ { "ecm:primaryType" : { "$in" : [ ... types without Foo nor Bar ...]}} ,
 *              { "ecm:mixinTypes" : { "$nin" : [ "Foo" , "Bar]}}]}
 * </pre>
 */
public DBObject walkMixinTypes(List<String> mixins, boolean include) {
    /*
     * Primary types that match.
     */
    Set<String> matchPrimaryTypes;
    if (include) {
        matchPrimaryTypes = new HashSet<>();
        for (String mixin : mixins) {
            matchPrimaryTypes.addAll(getMixinDocumentTypes(mixin));
        }
    } else {
        matchPrimaryTypes = new HashSet<>(getDocumentTypes());
        for (String mixin : mixins) {
            matchPrimaryTypes.removeAll(getMixinDocumentTypes(mixin));
        }
    }
    /*
     * Instance mixins that match.
     */
    Set<String> matchMixinTypes = new HashSet<>();
    for (String mixin : mixins) {
        if (!isNeverPerInstanceMixin(mixin)) {
            matchMixinTypes.add(mixin);
        }
    }
    /*
     * MongoDB query generation.
     */
    // match on primary type
    DBObject p = new BasicDBObject(DBSDocument.KEY_PRIMARY_TYPE,
            new BasicDBObject(QueryOperators.IN, matchPrimaryTypes));
    // match on mixin types
    // $in/$nin with an array matches if any/no element of the array matches
    String innin = include ? QueryOperators.IN : QueryOperators.NIN;
    DBObject m = new BasicDBObject(DBSDocument.KEY_MIXIN_TYPES, new BasicDBObject(innin, matchMixinTypes));
    // and/or between those
    String op = include ? QueryOperators.OR : QueryOperators.AND;
    return new BasicDBObject(op, Arrays.asList(p, m));
}

From source file:org.slc.sli.dal.convert.ContainerDocumentAccessor.java

License:Apache License

/**
 * Generate query criteria for the container-embedded doc (e.g. attendanceEvent) based on natural key fields
 * specified in schema for the 'embeddedDocType'.
 *
 * @param embeddedDocType//  w w w.  j av  a2 s .co m
 *        Container document type
 * @param doc
 *        Container-embedded document (e.g. single attendanceEvent)
 *
 * @return
 *        Query criteria for the container-embedded doc based on the natural key fields.
 */
private Map<String, Object> filterByNaturalKeys(String embeddedDocType, Map<String, Object> doc) {
    Map<String, Object> filteredDoc = new HashMap<String, Object>();
    List<Map<String, Object>> fieldCriteria = new ArrayList<Map<String, Object>>();

    // get natural key fields from schema
    NeutralSchema schema = schemaRepo.getSchema(embeddedDocType);

    // don't filter if the natural keys are unknown
    if (schema == null) {
        return doc;
    }

    // loop over natural key fields
    Map<String, NeutralSchema> fieldSchemas = schema.getFields();
    for (Map.Entry<String, NeutralSchema> fieldSchema : fieldSchemas.entrySet()) {
        AppInfo appInfo = (fieldSchema.getValue() == null) ? null : fieldSchema.getValue().getAppInfo();
        if (appInfo != null && appInfo.isNaturalKey()) {
            Map<String, Object> naturalKeyCriteria = new HashMap<String, Object>();
            if (doc.containsKey(fieldSchema.getKey())) {
                // add it to the update criteria
                naturalKeyCriteria.put(fieldSchema.getKey(), doc.get(fieldSchema.getKey()));
                fieldCriteria.add(naturalKeyCriteria);
            } else {
                Map<String, Object> nonExistCriteria = new HashMap<String, Object>();
                nonExistCriteria.put(QueryOperators.EXISTS, false);
                // explicitly exclude missing natural key fields
                naturalKeyCriteria.put(fieldSchema.getKey(), nonExistCriteria);
                fieldCriteria.add(naturalKeyCriteria);
            }
        }
    }

    filteredDoc.put(QueryOperators.AND, fieldCriteria);
    return filteredDoc;
}

From source file:org.tinygroup.mongodb.engine.MongoDbContext.java

License:GNU General Public License

public DBObject generateConditionObject(List<ConditionField> conditionFields) {
    DBObject conditionObject = new BasicDBObject();
    List<ConditionField> orLists = new ArrayList<ConditionField>();
    List<ConditionField> andLists = new ArrayList<ConditionField>();
    for (ConditionField conditionField : conditionFields) {
        if (isCollectionField(conditionField.getFieldId())) {
            if (conditionField.getConnectMode().equalsIgnoreCase(OR)) {
                orLists.add(conditionField);
            } else {
                andLists.add(conditionField);
            }//  w ww.j  a va 2  s.co m

        }
    }
    if (!CollectionUtil.isEmpty(andLists)) {
        BasicDBList andList = new BasicDBList();
        for (ConditionField conditionField : andLists) {
            addCondition(andList, conditionField);
        }
        if (andList.size() > 0) {
            conditionObject.put(QueryOperators.AND, andList);
        }
    }

    if (!CollectionUtil.isEmpty(orLists)) {
        BasicDBList list = new BasicDBList();
        for (ConditionField conditionField : orLists) {
            addCondition(list, conditionField);
        }
        if (list.size() > 0) {
            conditionObject.put(QueryOperators.OR, list);
        }

    }
    return conditionObject;

}