Example usage for com.mongodb BasicDBObject append

List of usage examples for com.mongodb BasicDBObject append

Introduction

In this page you can find the example usage for com.mongodb BasicDBObject append.

Prototype

@Override
public BasicDBObject append(final String key, final Object val) 

Source Link

Document

Add a key/value pair to this object

Usage

From source file:fr.cirad.web.controller.gigwa.base.AbstractVariantController.java

License:Open Source License

/**
 * This method returns the number of variants that match provided parameters.
 *
 * @param request the request/*from  ww w  . j  a  va 2s.co  m*/
 * @param sModule the module
 * @param projId the proj id
 * @param selectedVariantTypes the selected variant types
 * @param selectedSequences the selected sequences
 * @param selectedIndividuals the selected individuals
 * @param gtPattern the gt code
 * @param genotypeQualityThreshold the genotype quality threshold
 * @param readDepthThreshold the read depth threshold
 * @param missingData the missing data
 * @param minmaf the minmaf
 * @param maxmaf the maxmaf
 * @param minposition the minposition
 * @param maxposition the maxposition
 * @param alleleCount the allele count
 * @param geneName the gene name
 * @param variantEffects the variant effects
 * @param processID the process id
 * @return the long
 * @throws Exception the exception
 */
@RequestMapping(variantCountURL)
protected @ResponseBody long countVariants(HttpServletRequest request, @RequestParam("module") String sModule,
        @RequestParam("project") int projId, @RequestParam("variantTypes") String selectedVariantTypes,
        @RequestParam("sequences") String selectedSequences,
        @RequestParam("individuals") String selectedIndividuals, @RequestParam("gtPattern") String gtPattern,
        @RequestParam("genotypeQualityThreshold") Integer genotypeQualityThreshold,
        @RequestParam("readDepthThreshold") Integer readDepthThreshold,
        @RequestParam("missingData") Double missingData,
        @RequestParam(value = "minmaf", required = false) Float minmaf,
        @RequestParam(value = "maxmaf", required = false) Float maxmaf,
        @RequestParam("minposition") Long minposition, @RequestParam("maxposition") Long maxposition,
        @RequestParam("alleleCount") String alleleCount, @RequestParam("geneName") String geneName,
        @RequestParam("variantEffects") String variantEffects,
        @RequestParam("processID") final String processID) throws Exception {
    final ProgressIndicator progress = new ProgressIndicator(processID.substring(1 + processID.indexOf('|')),
            new String[0]);
    ProgressIndicator.registerProgressIndicator(progress);

    DBCollection tmpVarColl = getTemporaryVariantCollection(sModule, progress.getProcessId(),
            true /*empty it*/);
    try {
        String queryKey = getQueryKey(request, sModule, projId, selectedVariantTypes, selectedSequences,
                selectedIndividuals, gtPattern, genotypeQualityThreshold, readDepthThreshold, missingData,
                minmaf, maxmaf, minposition, maxposition, alleleCount, geneName, variantEffects);

        final MongoTemplate mongoTemplate = MongoTemplateManager.get(sModule);
        DBCollection cachedCountcollection = mongoTemplate.getCollection(MgdbDao.COLLECTION_NAME_CACHED_COUNTS);
        //         cachedCountcollection.drop();
        DBCursor countCursor = cachedCountcollection.find(new BasicDBObject("_id", queryKey));
        Long count = null;
        if (countCursor.hasNext()) {
            count = 0l;
            for (Object aPartialCount : ((BasicDBList) countCursor.next()
                    .get(MgdbDao.FIELD_NAME_CACHED_COUNT_VALUE)).toArray())
                count += (Long) aPartialCount;
        }
        LOG.debug((count == null ? "new" : "existing") + " queryKey hash: " + queryKey);
        if (count == null) {
            long before = System.currentTimeMillis();

            progress.addStep("Counting matching variants");
            String sRegexOrAggregationOperator = GenotypingDataQueryBuilder.getGenotypePatternToQueryMap()
                    .get(gtPattern);

            List<String> alleleCountList = alleleCount.length() == 0 ? null
                    : Arrays.asList(alleleCount.split(";"));

            GenotypingProject genotypingProject = mongoTemplate.findById(projId, GenotypingProject.class);
            if (genotypingProject.getAlleleCounts().size() != 1
                    || genotypingProject.getAlleleCounts().iterator().next() != 2) { // Project does not only have bi-allelic data: make sure we can apply MAF filter on selection
                boolean fExactlyOneNumberOfAllelesSelected = alleleCountList != null
                        && alleleCountList.size() == 1;
                boolean fBiAllelicSelected = fExactlyOneNumberOfAllelesSelected
                        && "2".equals(alleleCountList.get(0));
                boolean fMafRequested = (maxmaf != null && maxmaf < 50) || (minmaf != null && minmaf > 0);
                if (fMafRequested && !fBiAllelicSelected) {
                    progress.setError("MAF is only supported on biallelic data!");
                    return 0l;
                }
            }

            String actualSequenceSelection = selectedSequences;
            if (actualSequenceSelection.length() == 0) {
                ArrayList<String> externallySelectedSeqs = getSequenceIDsBeingFilteredOn(request, sModule);
                if (externallySelectedSeqs != null)
                    actualSequenceSelection = StringUtils.join(externallySelectedSeqs, ";");
            }

            boolean fNeedToFilterOnGenotypingData = needToFilterOnGenotypingData(sModule, projId,
                    sRegexOrAggregationOperator, genotypeQualityThreshold, readDepthThreshold, missingData,
                    minmaf, maxmaf, geneName, variantEffects);

            BasicDBList variantQueryDBList = buildVariantDataQuery(sModule, projId,
                    selectedVariantTypes.length() == 0 ? null : Arrays.asList(selectedVariantTypes.split(";")),
                    actualSequenceSelection.length() == 0 ? null
                            : Arrays.asList(actualSequenceSelection.split(";")),
                    minposition, maxposition, alleleCountList);
            if (variantQueryDBList.isEmpty()) {
                if (!fNeedToFilterOnGenotypingData && mongoTemplate.count(null, GenotypingProject.class) == 1)
                    count = mongoTemplate.count(new Query(), VariantData.class); // no filter whatsoever
            } else {
                if (!fNeedToFilterOnGenotypingData) { // filtering on variant features only: we just need a count
                    count = mongoTemplate.getCollection(mongoTemplate.getCollectionName(VariantData.class))
                            .count(new BasicDBObject("$and", variantQueryDBList));
                } else { // filtering on variant features and genotyping data: we need a list of variant IDs to restrict the genotyping data search to
                    long beforeAggQuery = System.currentTimeMillis();
                    progress.setProgressDescription("Filtering variants for count...");

                    DBCollection variantColl = mongoTemplate
                            .getCollection(mongoTemplate.getCollectionName(VariantData.class));
                    List<DBObject> pipeline = new ArrayList<DBObject>();
                    pipeline.add(new BasicDBObject("$match", new BasicDBObject("$and", variantQueryDBList)));
                    BasicDBObject projectObject = new BasicDBObject("_id", "$_id");
                    projectObject.put(
                            VariantData.FIELDNAME_REFERENCE_POSITION + "."
                                    + ReferencePosition.FIELDNAME_SEQUENCE,
                            "$" + VariantData.FIELDNAME_REFERENCE_POSITION + "."
                                    + ReferencePosition.FIELDNAME_SEQUENCE);
                    projectObject.put(
                            VariantData.FIELDNAME_REFERENCE_POSITION + "."
                                    + ReferencePosition.FIELDNAME_START_SITE,
                            "$" + VariantData.FIELDNAME_REFERENCE_POSITION + "."
                                    + ReferencePosition.FIELDNAME_START_SITE);
                    projectObject.put(VariantData.FIELDNAME_TYPE, "$" + VariantData.FIELDNAME_TYPE);
                    projectObject.put(VariantData.FIELDNAME_KNOWN_ALLELE_LIST,
                            "$" + VariantData.FIELDNAME_KNOWN_ALLELE_LIST);
                    pipeline.add(new BasicDBObject("$project", projectObject));
                    pipeline.add(new BasicDBObject("$out", tmpVarColl.getName()));
                    variantColl.aggregate(pipeline);

                    mongoTemplate.getDb().setWriteConcern(WriteConcern.ACKNOWLEDGED);
                    LOG.debug("Variant preliminary query found " + tmpVarColl.count() + " results in "
                            + (System.currentTimeMillis() - beforeAggQuery) / 1000f + "s");

                    progress.setProgressDescription(null);
                    if (tmpVarColl.count() == 0)
                        count = 0l; // no need to search any further
                }
            }

            if (count != null) {
                BasicDBObject dbo = new BasicDBObject("_id", queryKey);
                dbo.append(MgdbDao.FIELD_NAME_CACHED_COUNT_VALUE, new Long[] { count });
                cachedCountcollection.save(dbo);
            } else { // now filter on genotyping data
                List<String> selectedIndividualList = selectedIndividuals.length() == 0 ? null
                        : Arrays.asList(selectedIndividuals.split(";"));
                if (selectedIndividualList == null)
                    selectedIndividualList = getIndividualsInDbOrder(sModule, projId);

                GigwaSearchVariantsExportRequest gsvr = new GigwaSearchVariantsExportRequest();
                gsvr.setAlleleCount(alleleCount);
                if (minposition != null)
                    gsvr.setStart(minposition);
                if (maxposition != null)
                    gsvr.setEnd(maxposition);
                gsvr.setGeneName(geneName);
                gsvr.setReferenceName(selectedSequences);
                gsvr.setSelectedVariantTypes(selectedVariantTypes);
                gsvr.setVariantEffect(variantEffects);
                gsvr.setVariantSetId(sModule + ServiceInterface.ID_SEPARATOR + projId);

                gsvr.setMissingData(missingData);
                gsvr.setMinmaf(minmaf);
                gsvr.setMaxmaf(maxmaf);
                gsvr.setGtPattern(gtPattern);

                HashMap<String, Integer> annotationFieldThresholds = new HashMap<String, Integer>();
                annotationFieldThresholds.put(VCFConstants.GENOTYPE_QUALITY_KEY, genotypeQualityThreshold);
                annotationFieldThresholds.put(VCFConstants.DEPTH_KEY, readDepthThreshold);
                gsvr.setAnnotationFieldThresholds(annotationFieldThresholds);
                gsvr.setCallSetIds(selectedIndividualList);

                GenotypingDataQueryBuilder genotypingDataQueryBuilder = new GenotypingDataQueryBuilder(gsvr,
                        tmpVarColl);
                try {
                    final int nChunkCount = genotypingDataQueryBuilder.getNumberOfQueries();
                    if (nChunkCount > 1)
                        LOG.debug("Query split into " + nChunkCount);

                    final Long[] partialCountArray = new Long[nChunkCount];
                    final Builder aggOpts = AggregationOptions.builder().allowDiskUse(false);
                    final ArrayList<Thread> threadsToWaitFor = new ArrayList<Thread>();
                    final AtomicInteger finishedThreadCount = new AtomicInteger(0);

                    ArrayList<List<DBObject>> genotypingDataPipelines = new ArrayList();
                    while (genotypingDataQueryBuilder.hasNext())
                        genotypingDataPipelines.add(genotypingDataQueryBuilder.next());

                    ArrayList<Integer> chunkIndices = new ArrayList<Integer>();
                    for (int i = 0; i < genotypingDataPipelines.size(); i++)
                        chunkIndices.add(i);
                    Collections.shuffle(chunkIndices);

                    for (int i = 0; i < chunkIndices.size()/*/2*/; i++) {
                        final List<DBObject> genotypingDataPipeline = genotypingDataPipelines
                                .get(chunkIndices.get(i));

                        // Now the $group operation, used for counting
                        DBObject groupFields = new BasicDBObject("_id", null);
                        groupFields.put("count", new BasicDBObject("$sum", 1));
                        genotypingDataPipeline.add(new BasicDBObject("$group", groupFields));

                        if (i == 0 && tmpVarColl.count() <= 5)
                            LOG.debug(genotypingDataPipeline);

                        if (progress.hasAborted()) {
                            genotypingDataQueryBuilder.cleanup(); // otherwise a pending db-cursor will remain
                            return 0l;
                        }

                        final int chunkIndex = i;

                        Thread t = new Thread() {
                            public void run() {
                                //                               long b4 = System.currentTimeMillis();
                                Cursor it = mongoTemplate
                                        .getCollection(MongoTemplateManager
                                                .getMongoCollectionName(VariantRunData.class))
                                        .aggregate(genotypingDataPipeline, aggOpts.build());
                                partialCountArray[chunkIndex] = it.hasNext()
                                        ? ((Number) it.next().get("count")).longValue()
                                        : 0;
                                progress.setCurrentStepProgress(
                                        (short) (finishedThreadCount.incrementAndGet() * 100 / nChunkCount));
                                //                           System.out.println("chunk " + chunkIndex + " took " + (System.currentTimeMillis() - b4));
                                genotypingDataPipeline.clear(); // release memory (VERY IMPORTANT)
                            }
                        };

                        if (i % NUMBER_OF_SIMULTANEOUS_QUERY_THREADS == (NUMBER_OF_SIMULTANEOUS_QUERY_THREADS
                                - 1)) {
                            t.run(); // run synchronously
                        } else {
                            threadsToWaitFor.add(t);
                            t.start(); // run asynchronously for better speed
                        }
                    }

                    for (Thread t : threadsToWaitFor) // wait for all threads before moving to next phase
                        t.join();

                    progress.setCurrentStepProgress(100);

                    count = 0l;
                    for (Long partialCount : partialCountArray)
                        count += partialCount;

                    BasicDBObject dbo = new BasicDBObject("_id", queryKey);
                    dbo.append(MgdbDao.FIELD_NAME_CACHED_COUNT_VALUE, partialCountArray);
                    cachedCountcollection.save(dbo);
                } catch (Exception e) {
                    genotypingDataQueryBuilder.cleanup(); // otherwise a pending db-cursor will remain
                    throw e;
                }
            }
            LOG.info("countVariants found " + count + " results in "
                    + (System.currentTimeMillis() - before) / 1000d + "s");
        }

        progress.markAsComplete();
        if (progress.hasAborted())
            return 0l;

        return count;
    } finally {
        //         getTemporaryVariantCollection(sModule, progress.getProcessId(), true);   // always empty it
    }
}

From source file:fr.cnes.sitools.dataset.database.mongodb.RequestMongoDB.java

License:Open Source License

@Override
public String getAttributes(List<Column> columnVisible) {
    BasicDBObject keys = new BasicDBObject();
    boolean foundId = false;
    for (Column column : columnVisible) {
        if (ID_COLUMN_NAME.equals(column.getDataIndex())) {
            foundId = true;/*ww  w  . jav a  2  s.c  o  m*/
        }
        keys.append(column.getDataIndex(), 1);
    }
    if (!foundId) {
        keys.append(ID_COLUMN_NAME, 0);
    }

    return keys.toString();
}

From source file:fr.cnes.sitools.dataset.database.mongodb.RequestMongoDB.java

License:Open Source License

@Override
public String getFilterClause(List<Predicat> predicats, List<Column> columns) {
    BasicDBObject whereClause = new BasicDBObject();
    // loop over the predicats
    // boolean first = true;
    // String result = "{";
    ////  ww  w . j a  va  2 s  .  com
    // Map<String, List<Predicat>> orderedPredicats = orderPredicat(predicats);
    // for (Predicat predicat : predicats) {
    //
    // String filter = getFilter(predicat);
    // if (filter != null && !"".equals(filter)) {
    // // DBObject objPredicat = (DBObject) JSON.parse(filter);
    // // if (objPredicat != null) {
    // if (first) {
    // whereClause.append("$and", new ArrayList<DBObject>());
    // }
    // else {
    // result += ",";
    // }
    // first = false;
    //
    // result += filter;
    //
    // // ((List<DBObject>) whereClause.get("$and")).add(objPredicat);
    //
    // // if (whereClause.containsField(key)) {
    // // // If the key already exists append the value to the existing key
    // // // DBObject obj = new BasicDBObject();
    // // // obj.put("$and", objPredicat.get(key));
    // //
    // // if (!whereClause.containsField("$and")) {
    // // whereClause.append("$and", new ArrayList<DBObject>());
    // // DBObject pred = (DBObject) whereClause.get(key);
    // // whereClause.remove(key);
    // // ((List<DBObject>) whereClause.get("$and")).add(pred);
    // //
    // // }
    // // ((List<DBObject>) whereClause.get("$and")).add(objPredicat);
    // //
    // // // ((DBObject) whereClause.get(key)).putAll(obj);
    // // }
    // // else {
    // // // if the key doesn't exists just append the predicat to the whereClause
    // // whereClause.append(key, objPredicat.get(key));
    // // }
    //
    // }
    // // }
    // }

    for (Predicat predicat : predicats) {
        String filter = getFilter(predicat);
        if (filter != null && !"".equals(filter)) {
            DBObject objPredicat = (DBObject) JSON.parse(filter);
            if (objPredicat != null) {
                Set<String> keys = objPredicat.keySet();
                for (String key : keys) {
                    if (whereClause.containsField(key)) {
                        ((DBObject) whereClause.get(key)).putAll((DBObject) objPredicat.get(key));
                    } else {
                        whereClause.append(key, objPredicat.get(key));
                    }

                }
            }
        }
    }

    return whereClause.toString();
}

From source file:fr.cnes.sitools.dataset.database.mongodb.RequestMongoDB.java

License:Open Source License

@Override
public String getOrderBy(DataSet ds) {
    BasicDBObject orderBy = new BasicDBObject();
    List<Column> columnsOrderBy = ds.getColumnOrderBy();
    if (columnsOrderBy != null && columnsOrderBy.size() != 0) {
        for (Column column : columnsOrderBy) {
            int orderDir;
            if ("ASC".equals(column.getOrderBy())) {
                orderDir = 1;// w  w  w.  ja  v a 2s.  c  o m
            } else {
                orderDir = -1;
            }
            orderBy.append(column.getDataIndex(), orderDir);
        }
    }
    return orderBy.toString();
}

From source file:fr.cnes.sitools.dataset.database.mongodb.RequestMongoDB.java

License:Open Source License

/**
 * Get the Sorting Order for the given {@link Multisort} as a String
 * /* w  ww. j a va  2  s .c  om*/
 * @param multisort
 *          the sort order definition
 * @return the Sorting order as a String
 */
public String getOrderBy(Multisort multisort) {
    BasicDBObject orderBy = new BasicDBObject();
    Sort[] sorts = multisort.getOrdersList();
    if (sorts != null && sorts.length != 0) {
        for (int i = 0; i < sorts.length; i++) {
            Sort sort = sorts[i];
            int orderDir;
            if (SortOrder.ASC.equals(sort.getDirection())) {
                orderDir = 1;
            } else {
                orderDir = -1;
            }
            orderBy.append(sort.getField(), orderDir);
        }

    }
    return orderBy.toString();
}

From source file:fr.gouv.vitam.cases.ElasticSearchAccess.java

License:Open Source License

private static final BasicDBObject getFiltered(final BSONObject bson) {
    BasicDBObject maip = new BasicDBObject();
    maip.putAll(bson);/*from  w  ww  .  j av  a 2  s  . co m*/
    maip.removeField(VitamLinks.DAip2DAip.field1to2);
    // Keep it maip.removeField(VitamLinks.DAip2DAip.field2to1);
    //maip.removeField(VitamLinks.Domain2DAip.field2to1);
    //maip.removeField(VitamLinks.DAip2Dua.field1to2);
    //maip.removeField(VitamLinks.DAip2PAip.field1to2);
    // maip.removeField(ParserIngest.REFID);
    // DOMDEPTH already ok but duplicate it
    @SuppressWarnings("unchecked")
    final HashMap<String, Integer> map = (HashMap<String, Integer>) maip.get(DAip.DAIPDEPTHS);
    //final List<String> list = new ArrayList<>(map.keySet());
    maip.append(DAip.DAIPPARENTS, map.keySet());// was list);
    return maip;
}

From source file:fr.gouv.vitam.cases.PAip.java

License:Open Source License

@Override
protected boolean updated(final CassandraAccess dbvitam) {
    final PAip vt = (PAip) dbvitam.paips.collection.findOne(getId());
    BasicDBObject update = null;
    if (vt != null) {
        final List<DBObject> list = new ArrayList<>();
        BasicDBObject upd = dbvitam.updateLinks(this, vt, VitamLinks.DAip2PAip, false);
        if (upd != null) {
            list.add(upd);//from w ww .  j  a v a  2  s.  com
        }
        upd = dbvitam.updateLink(this, vt, VitamLinks.PAip2Dua, true);
        if (upd != null) {
            list.add(upd);
        }
        if (!list.isEmpty()) {
            try {
                update = new BasicDBObject();
                if (!list.isEmpty()) {
                    upd = new BasicDBObject();
                    for (final DBObject dbObject : list) {
                        upd.putAll(dbObject);
                    }
                    update = update.append("$addToSet", upd);
                }
                dbvitam.paips.collection.update(new BasicDBObject(ID, this.get(ID)), update);
            } catch (final MongoException e) {
                LOGGER.error("Exception for " + update, e);
                throw e;
            }
            list.clear();
        }
        return true;
    } else {
        dbvitam.updateLinks(this, null, VitamLinks.DAip2PAip, false);
    }
    return false;
}

From source file:fr.gouv.vitam.cbes.ResultCached.java

License:Open Source License

@SuppressWarnings("unchecked")
@Override// w  w w .jav  a  2 s . com
protected boolean updated(final CouchbaseAccess dbvitam) {
    final ResultCached vt = (ResultCached) dbvitam.findOne(VitamCollections.Crequests, getId());
    if (vt != null) {
        final List<DBObject> list = new ArrayList<DBObject>();
        final List<String> slist = (List<String>) vt.get(CURRENTDAIP);
        if (slist != null) {
            final Set<String> newset = new HashSet<String>(currentDaip);
            newset.removeAll(currentDaip);
            if (!newset.isEmpty()) {
                list.add(new BasicDBObject(CURRENTDAIP, new BasicDBObject("$each", newset)));
            }
        }
        if (!list.isEmpty()) {
            final BasicDBObject upd = new BasicDBObject();
            for (final DBObject dbObject : list) {
                upd.putAll(dbObject);
            }
            upd.append(MINLEVEL, minLevel);
            upd.append(MAXLEVEL, maxLevel);
            upd.append(NBSUBNODES, nbSubNodes);
            final BasicDBObject update = new BasicDBObject("$addToSet", upd);
            // XXX FIXME cannot make an update
            //dbvitam.requests.collection.update(new BasicDBObject(ID, this.get(ID)), update);
        }
    }
    return false;
}

From source file:fr.gouv.vitam.mdbes.CopyOfResultMongodb.java

License:Open Source License

@SuppressWarnings("unchecked")
protected boolean updated(final MongoDbAccess dbvitam) {
    if (getId() == null) {
        return false;
    }//  w  w w.ja va  2 s  .c  o m
    final CopyOfResultMongodb vt = (CopyOfResultMongodb) dbvitam.requests.collection.findOne(getId());
    if (vt != null) {
        final List<DBObject> list = new ArrayList<DBObject>();
        final Object obj = vt.obj.get(CURRENTDAIP);
        final Set<String> vtset = new HashSet<String>();
        if (obj instanceof BasicDBList) {
            for (Object string : (BasicDBList) obj) {
                vtset.add((String) string);
            }
        } else {
            vtset.addAll((Set<String>) obj);
        }
        if (!vtset.isEmpty()) {
            final Set<String> newset = new HashSet<String>(currentDaip);
            newset.removeAll(vtset);
            if (!newset.isEmpty()) {
                list.add(new BasicDBObject(CURRENTDAIP, new BasicDBObject("$each", newset)));
            }
        }
        if (!list.isEmpty()) {
            final BasicDBObject updset = new BasicDBObject();
            for (final DBObject dbObject : list) {
                updset.putAll(dbObject);
            }
            final BasicDBObject upd = new BasicDBObject();
            upd.append(MINLEVEL, minLevel);
            upd.append(MAXLEVEL, maxLevel);
            upd.append(NBSUBNODES, nbSubNodes);
            upd.append(TTL, ttl);
            final BasicDBObject update = new BasicDBObject("$addToSet", updset).append("$set", upd);
            dbvitam.requests.collection.update(new BasicDBObject(ID, this.obj.get(ID)), update);
        }
        if (GlobalDatas.PRINT_REQUEST) {
            LOGGER.warn("UPDATE: " + this);
        }
    } else if (obj.containsField(ID)) {
        // not in DB but got already an ID => Save it
        if (GlobalDatas.PRINT_REQUEST) {
            LOGGER.warn("SAVE: " + this);
        }
        this.forceSave(dbvitam.requests);
        return true;
    }
    return false;
}

From source file:fr.gouv.vitam.mdbes.DAip.java

License:Open Source License

@Override
protected boolean updated(final MongoDbAccess dbvitam) {
    final DAip vt = (DAip) dbvitam.daips.collection.findOne(getString(ID));
    BasicDBObject update = null;/*from w  ww  .  j  av a  2 s.c om*/
    if (vt != null) {
        LOGGER.debug("UpdateLinks: {}\n\t{}", this, vt);
        final List<DBObject> list = new ArrayList<>();
        final List<DBObject> listset = new ArrayList<>();
        /*
         * Only parent link, not child link
         * BasicDBObject upd = dbvitam.updateLinks(this, vt, VitamLinks.DAip2DAip, true);
         * if (upd != null) {
         * list.add(upd);
         * }
         */
        BasicDBObject upd = dbvitam.updateLinks(this, vt, VitamLinks.DAip2DAip, false);
        if (upd != null) {
            list.add(upd);
        }
        upd = dbvitam.updateLinks(this, vt, VitamLinks.Domain2DAip, false);
        if (upd != null) {
            list.add(upd);
        }
        upd = dbvitam.updateLink(this, vt, VitamLinks.DAip2PAip, true);
        if (upd != null) {
            listset.add(upd);
        }
        upd = dbvitam.updateLink(this, vt, VitamLinks.DAip2Dua, true);
        if (upd != null) {
            listset.add(upd);
        }
        // DAIPDEPTHS
        @SuppressWarnings("unchecked")
        final HashMap<String, Integer> vtDom = (HashMap<String, Integer>) vt.removeField(DAIPDEPTHS);
        @SuppressWarnings("unchecked")
        HashMap<String, Integer> domainelevels = (HashMap<String, Integer>) get(DAIPDEPTHS);
        if (domainelevels == null) {
            domainelevels = new HashMap<String, Integer>();
        }
        final BasicDBObject vtDomaineLevels = new BasicDBObject();
        if (vtDom != null) {
            // remove all not in current but in vt as already updated, for the others compare vt with current
            for (final String dom : vtDom.keySet()) {
                final Integer pastval = vtDom.get(dom);
                final Integer newval = domainelevels.get(dom);
                if (newval != null) {
                    if (pastval > newval) {
                        vtDomaineLevels.append(dom, newval); // to be remotely updated
                    } else {
                        vtDomaineLevels.append(dom, pastval); // to be remotely updated
                        domainelevels.put(dom, pastval); // update only locally
                    }
                } else {
                    vtDomaineLevels.append(dom, pastval); // to be remotely updated
                    domainelevels.put(dom, pastval); // update only locally
                }
            }
            // now add into remote update from current, but only non existing in vt (already done)
            for (final String dom : domainelevels.keySet()) {
                // remove by default
                final Integer srcobj = vtDom.get(dom);
                final Integer obj = domainelevels.get(dom);
                if (srcobj == null) {
                    vtDomaineLevels.append(dom, obj); // will be updated remotely
                }
            }
            // Update locally
            append(DAIPDEPTHS, domainelevels);
        }
        if (!vtDomaineLevels.isEmpty()) {
            upd = new BasicDBObject(DAIPDEPTHS, vtDomaineLevels);
            listset.add(upd);
        }
        try {
            update = new BasicDBObject();
            if (!list.isEmpty()) {
                upd = new BasicDBObject();
                for (final DBObject dbObject : list) {
                    upd.putAll(dbObject);
                }
                update = update.append("$addToSet", upd);
            }
            if (!listset.isEmpty()) {
                upd = new BasicDBObject();
                for (final DBObject dbObject : listset) {
                    upd.putAll(dbObject);
                }
                update = update.append("$set", upd);
            }
            update = update.append("$inc", new BasicDBObject(NBCHILD, nb));
            nb = 0;
            dbvitam.daips.collection.update(new BasicDBObject(ID, this.get(ID)), update);
        } catch (final MongoException e) {
            LOGGER.error("Exception for " + update, e);
            throw e;
        }
        list.clear();
        listset.clear();
        return true;
    } else {
        // dbvitam.updateLinks(this, null, VitamLinks.DAip2DAip, true);
        dbvitam.updateLinks(this, null, VitamLinks.DAip2DAip, false);
        dbvitam.updateLinks(this, null, VitamLinks.Domain2DAip, false);
        append(NBCHILD, nb);
        nb = 0;
    }
    return false;
}