如何使用mongoDb java异步驱动程序在插入到mongoDb集合后获取_id
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;
}
}
}其中FeedMongoDTO的结构如下所示
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;
}
}我需要获取_id的值,但这里的d1.get("id").toString()导致了NullPointerException
还有一件事,我很困惑是否正确地使用了Save()方法。使用普通的mongodb驱动程序会更容易。
public String save(FeedMongoDTO feed, String collectionName) {
try {
mongoTemplate.save(feed, collectionName);
return feed.getId();
} catch (Exception ex) {
return null;
}
} 提前感谢
Abhilash :)
发布于 2014-10-30 09:30:13
如果这是您经常需要做的事情,为什么不自己设置_id呢?您可以使用0-arg构造函数轻松构造一个新的ObjectId,只需在插入之前将其添加到文档中即可。
ObjectId id = new ObjectId();
documentBuilder.add("_id", id);
collection.insert(documentBuilder);仅仅为了检索id而运行单独的查询似乎很愚蠢。
发布于 2013-03-26 04:03:07
在我看来,异步java驱动程序提供了进行同步查询的方法,例如使用正常的findOne调用。这对你的需求有意义吗?
发布于 2015-08-15 09:51:43
当我用我的异步节点应用在我的目录中创建一个新名称时,我自己遇到了这个问题。我想通过用户的ID将用户带到新创建的名称,而不是将用户返回到目录列表。allTwentyQuestions在这方面做得很对,但对Node来说并不完全正确,并引导我走上了这条道路:
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);
}
});
}然后我会从我的应用程序中调用该函数:
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);
}
});https://stackoverflow.com/questions/15623492
复制相似问题