I'm trying to insert a single ArrayList containing JSONS into a mongodb collection with this,
MongoClient mongo = new MongoClient("localhost", 27017);
DB db = mongo.getDB("structure");
DBCollection collection = db.getCollection("chapter");
List<Document> data = new ArrayList<>();
collection.insertMany(data);
String str = "[{\"id\":1,\"data\":\"data1\"},{\"id\":2,\"data\":\"data2\"}]";
DBObject dbObject = (DBObject) JSON.parse(str);
collection.insert(dbObject);
But I get the exception,
Exception in thread "main" java.lang.IllegalArgumentException: BasicBSONList can only work with numeric keys, not: [_id]
Can anyone show me the correct way to do this?
Insert ArrayList mongodb
The question above is about bulk insert of JSONS, not as a single one.
My question is unique
The exception gives a hint of what the problem is: a list cannot be used as a record (or a map-like data structure).
To quote the MongoDB documentation on documents that compose a collection:
Document Structure
MongoDB documents are composed of field-and-value
pairs and have the following structure:
{
field1: value1,
field2: value2,
field3: value3,
...
fieldN: valueN
}
So what you need to do, in your case, because you just want to insert many documents in one call, is to use collection.insertMany:
List<Document> documents = ...; //convert your list to a List<Document>
collection.insertMany(documents);
Have a look at this
https://docs.mongodb.com/manual/reference/method/db.collection.insertMany/
List<DBobject> data = new ArrayList<>();
Colletions.insertMany(data);
Related
I want to select a specific field of a document in Mongodb collection and convert it to java object.
My document is like this:
{
"Name":"Ben",
"template":"A fingerprint template which I extracted"
}
So I wish select this "template field"
My sample code is below:
List<Document> documents = (List<Document>) collection.find().into(new ArrayList<Document>());
for (Document document : documents) {
Document doc = documents.get(document);
FingerprintTemplate template = (FingerprintTemplate) doc.get("template");
And the error is:
java: incompatible types: org.bson.Document cannot be converted to int
Any idea or any suggestions please!!
You can query if the field exists:
collection.find("template": { $exists: true, $ne: null } });
For the mapping part, you can have a look at objectMapper to map directly to a java object: https://www.baeldung.com/jackson-object-mapper-tutorial
Your error is still that you have a Document and Java is expecting an int.
Try this :
BasicDBObject query = new BasicDBObject();
BasicDBObject whereQuery = new BasicDBObject();
basicDBObject.put("template",1);
DBCursor cursor = collection.find(query,whereQuery);
while(cursor.hasNext()) {
System.out.println(cursor.next());
}
This would print the documents that have template but to convert to Object you would need some JSON Object mapper maybe jackson
I am trying to query a mongodb collection and retrieve certain documents based on a field value but also only retrieve a single field per record. I tried the following but no getting the solution I want:
MongoCollection<Document> collection =
database.getCollection("client_data");
//Document document = collection
// .find(new BasicDBObject("sampleUser", "myDb"))
//.projection(Projections.fields(Projections.include("address"),
//Projections.excludeId())).first();
BasicDBObject aQuery = new BasicDBObject();
aQuery.put("clientId",567);
FindIterable<Document> iterDoc = collection.find(aQuery);
The following retrieves all documents for clientid = 567, but I only want to show the address field.
The commented out code was also what I tried but not sure how to combine that with the query.
EDIT:
I am now able to iterate through all the results but would like to parse each document; I tried parsing the document into my class object but it immediately gives an error:
Unrecognized field "_id" (class
model.Client), not marked as ignorable
But _id is the very first field in the document:
Document{{_id=6216a7f64cedfd00011c35a5,
So I tried something else rather using the first document but then I don't know how to get the next document:
while(cursor.hasNext()) {
// System.out.println(cursor.next().toJson());
Client client = new Client();
try {
JsonParser jsonParser = new JsonFactory().createParser(cursor.next().toJson());
ObjectMapper mapper = new ObjectMapper();
ObjectNode rootNode = mapper.createObjectNode();
String customerInfo = fi.first().toJson();
JsonNode jobj = mapper.readTree(customerInfo);
// this gives the error// client = mapper.readValue(jsonParser,Client.class);
client.setId(jobj.path("_id").path("$oid").asText());
Please advise.
In order to:
retrieves all documents for clientid = 567, but I only want to show the address field
You would execute the following:
collection
.find(Filters.eq("clientId", 567))
.projection(Projections.fields(
Projections.include("address"),
Projections.excludeId())
).first()
Breaking it down:
.find(Filters.eq("clientId", 567)): apply the predicate 'where clientId = 567'
.projection(Projections.fields(Projections.include("address"), Projections.excludeId())): let the response include the address field and exclude the _id field
I need to replace a whole existing document of mongodb from java instead of setting every field.Is there any way? I am using mongo morphia.
Right now i am setting fields one by one ,following is code :
DBObject searchObject =new BasicDBObject();
searchObject.put("procId", procId);
final UpdateOperations<Timesheet> updateOperations = ds.createUpdateOperations(Timesheet.class)
.set("wheelInTime", timesheet.getWheelInTime())
.set("wheelOutTime", timesheet.getWheelOutTime())
.set("tableOnTime", timesheet.getTableOnTime())
.set("tableOffTime", timesheet.getTableOffTime())
final UpdateResults results = ds.updateFirst(findQuery,updateOperations);
You can 'overwrite' any entry in a MongoDB collection but simply creating a new DbObject with the same _id field and saving it to the database. So just set the fields in your object as you would any Java object and use myCollection.save(obj)
Just save the object and it will overwrite the document with the same #id. This can be done with one line of code:
dao.save(timesheet);
More complete example code of the usage of the Morphia DAO:
class Dao extends BasicDAO<TimeSheet, String> {
Dao(Datastore ds) {
super(TimeSheet.class, ds);
}
}
Datastore ds = morphia.createDatastore(mongoClient, DB_NAME);
Dao dao = new Dao(ds);
dao.save(timesheet);
I am trying to get the Data from Mongodb whose Model/Domain is unknown.
Can i get that using Mongo Template.
e.g.
mongoTemplate.find(query,<Dynamic Class?>)
You can use DBObject. If you take a look at its implementations (BasicDBObject...) it's an HashMap (key/values) containing all fields:
#Autowired
private MongoTemplate mongoTemplate;
DBObject query = new BasicDBObject("field", "value");
DBCursor dbCursor = mongoTemplate.getCollection("collectionName").find(query);
Iterator<DBObject> iterator = dbCursor.iterator();
while(iterator.hasNext()){
Object value = iterator.next().get("otherfield");
}
How do I search through mongodb documents where documents have nested documents. For example I have a collection of private messages. Each private message has two nested documents - one representing the sending user and the other representing the receiving use. Both nested documents have the form -
userID: 34343,
name: Joe Bloggs
I would like to be able to search for all mail messages sent by a user (e.g. search the sender user nested document).
I am using the java driver. Do I need to create a DBObject which represents the nested document?
Thanks
As i understand u have document structure like this:
{
"someProperty" : 1,
"sendingUser" : {
userID : 34343,
name : "Joe Bloggs"
},
"recivingUser" : {
userID : 34345,
name : "Joe Bloggs"
}
}
So if you need find sending user with userID = 34345 you just need do following(i just think that is so, because actually i am working with c# driver for mongo):
DBCollection coll = db.getCollection("privateMessages")
query = new BasicDBObject();
query.put("sendingUser.userID", new BasicDBObject("$eq", 34345));
cur = coll.find(query); // all documents with sendingUser.userID = 34345 will be //returned by cursor
Also check tutorial for java driver
For MongoDB Java Driver v3.2.2. You can do something like this:
FindIterable<Document> iterable = collection.find(Document.parse("{\"sendingUser.userID\": \"34343\"}"));
FindIterable<Document> iterable = collection.find(Document.parse("{\"sendingUser.name\": \"Joe Bloggs\"}"));
You can put the $eq inside the JSON style query string. Like { <field>: { $eq: <value> } }.