简体   繁体   中英

How to get _id after insertion to mongoDb collection using mongoDb java asynchronous driver

How to get _id after insertion to mongoDb collection using mongoDb java asynchronous driver

package test;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.allanbank.mongodb.MongoClient;
import com.allanbank.mongodb.MongoClientConfiguration;
import com.allanbank.mongodb.MongoCollection;
import com.allanbank.mongodb.MongoDatabase;
import com.allanbank.mongodb.MongoFactory;
import com.allanbank.mongodb.bson.Document;
import com.allanbank.mongodb.bson.builder.BuilderFactory;
import com.allanbank.mongodb.bson.builder.DocumentBuilder;
import com.allanbank.mongodb.builder.Aggregate;
import com.xxxx.dto.FeedMongoDTO;

/**
* @author abhi
* 
*/
public class MongoTestService {

public static transient Log log = LogFactory.getLog(FeedMongoOperations.class);

private MongoClient mongo;
private MongoDatabase db;
private MongoCollection collection;

public boolean openDbConnection() {
    try {
        MongoClientConfiguration config = new MongoClientConfiguration();
        config.addServer("localhost:27017");
        config.setMaxConnectionCount(10);

        mongo = MongoFactory.createClient(config);

        db = mongo.getDatabase("feedDatabase");

        return true;
    } catch (Exception e) {
        return false;
    }
}

public boolean closeDbConnection() {
    try {
        mongo.close();
        return true;
    } catch (Exception e) {
        return false;
    }
}

public String save(FeedMongoDTO feed, String collectionName) {
    try {

        collection = db.getCollection(collectionName);
        DocumentBuilder b = BuilderFactory.start();
        Document d1 = b.add("url", feed.getUrl()).addLong("mongoTimeStamp", feed.getMongoTimestamp())
                .add("feedJsonArray", feed.getFeedJsonArray()).build();

        collection.insert(d1);

        return d1.get("id").toString();
    } catch (Exception ex) {
        return null;
    }
}

public FeedMongoDTO getFeed(String mongoId, String collectionName) {

    FeedMongoDTO feedMongoDTO = null;

    try {
        return feedMongoDTO;
    } catch (Exception ex) {
        return null;
    }
}
}

Where FeedMongoDTO has the structure as given below

public class FeedMongoDTO {

    private String id;
    private String url;
    private Long mongoTimeStamp;
    private JSONArray feedJsonArray;

    //  Getters 
    public String getId() {
        return id;
    }

    public String getUrl() {
        return url;
    }

    public Long getMongoTimestamp() {
        return mongoTimeStamp;
    }

    public JSONArray getFeedJsonArray() {
        return feedJsonArray;
    }


    //  Setters 
    public void setId(String id) {
        this.id = id;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public void setMongoTimestamp(Long mongoTimestamp) {
        this.mongoTimeStamp = mongoTimestamp;
    }

    public void setFeedJsonArray(JSONArray feedJsonArray) {
        this.feedJsonArray = feedJsonArray;
    }

}

I need to get the value of _id but here d1.get("id").toString() is causing NullPointerException

And one more thing I am confused whether I am doing the Save() method correctly. Using usual mongodb driver it was pretty much easier.

public String save(FeedMongoDTO feed, String collectionName) {
    try {
        mongoTemplate.save(feed, collectionName);
        return feed.getId();
    } catch (Exception ex) {
        return null;
    } 
} 

thanks in advance

Abhilash :)

If this is something you need to do often, why not just set the _id yourself. You can easily construct a new ObjectId by using the 0-arg constructor, and just add it to your document before inserting it.

ObjectId id = new ObjectId();
documentBuilder.add("_id", id);
collection.insert(documentBuilder);

Seems silly to run a separate query just to retrieve the id.

It seems to me that the asynchronous java driver provides ways of making synchronous queries, such as with the normal findOne call. Does this make sense for your needs?

I ran into this myself when creating a new Name in my directory with my Asynchronous Node App. I wanted to take the user to the newly created Name via it's ID without throwing the user back to the directory list. allTwentyQuestions got this kind of right, though not quite right for Node, and led me on this path:

addName: function(nameDB, newName, callback){
  nameID = new require('mongodb').ObjectID();
  nameDB.collection('nameList').insert({"_id" : nameID, 'Name' : newName, 'type' : '', 'active' : 'no', 'modifiedDate' : ''}, function(err, result) {
    if (!err) {
        // success
        callback(null, nameID);
    } else {
        // error
        callback('error', err);
    }
  });
}

I would then call the function from my app:

mongo.addName(nameDB, newName, function(err, result) {
  if (!err){
    // success
    // direct the user to the proper page with this new ObjectID found in the var 'result'
  } else {
    // error
    console.log('There was an error adding the name: '+ result);
  }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM