MongoDB update using Java 3 driver - mongodb-java

I'm switching to the MongoDB Java driver version 3. I cannot figure out how to perform an update of a Document. For example, I want to change the "age" of an user:
MongoDatabase db = mongoClient.getDatabase("exampledb");
MongoCollection<org.bson.Document> coll = db.getCollection("collusers");
Document doc1 = new Document("name", "frank").append("age", 55) .append("phone", "123-456-789");
Document doc2 = new Document("name", "frank").append("age", 33) .append("phone", "123-456-789");
coll.updateOne(doc1, doc2);
The output is:
java.lang.IllegalArgumentException: Invalid BSON field name name
Any idea how to fix it ?
Thanks!

Use:
coll.updateOne(eq("name", "frank"), new Document("$set", new Document("age", 33)));
for updating the first Document found. For multiple updates:
coll.updateMany(eq("name", "frank"), new Document("$set", new Document("age", 33)));
On this link, you can fine a quick reference to MongoDB Java 3 Driver

in Mongodb Java driver 3.0 , when you update a document, you can call the coll.replaceOne method to replace document, or call the coll.updateOne / coll.updateMany method to update document(s) by using $set/$setOnInsert/etc operators.
in your case, you can try:
coll.updateOne(eq("name", "frank"), new Document("$set", new Document("age", 33)));
coll.replaceOne(eq("name", "frank"), new Document("age", 33));

You can try this
coll.findOneAndReplace(doc1, doc2);

Related

Cannot create index in JanusGraph

I've installed JanusGraph 0.5.2 with ScyllaDB 4.2.1 and Elasticsearch 6.6.0 and I'm trying to create a fulltext index according to the docs as follows:
1. mgmt = graph.openManagement()
2. PropertyKey value = mgmt.makePropertyKey('value').dataType(String.class).make()
3. mgmt.buildIndex('verticesByValue', Vertex.class).addKey(value, Mapping.TEXT.asParameter()).buildMixedIndex("search")
4. mgmt.commit()
It throws this error after I enter the 3. step:
No signature of method: org.janusgraph.graphdb.database.management.ManagementSystem$IndexBuilder.addKey() is applicable for argument types: (org.apache.tinkerpop.gremlin.structure.T$4, org.janusgraph.core.schema.Parameter) values: [value, mapping->TEXT]
Instead of:
PropertyKey value = mgmt.makePropertyKey('value').dataType(String.class).make()
Use This:
value = mgmt.makePropertyKey('value').dataType(String.class).make()
I was able to generate the issue when I used "PropertyKey" type to assign to value.

Elasticsearch - Convert Json Strin to XcontentBuilder

I was using elasticsearch 6.2.2. and this is how I convert json string to Xcontentbuilder.
XContentBuilder builder = JsonXContent.contentBuilder().prettyPrint();
XContentParser parser = JsonXContent.jsonXContent.createParser(NamedXContentRegistry.EMPTY, jsonObj.toString());
builder.copyCurrentStructure(parser);
I worked well until I updated elasticsearch 6.3+.
There is error on ES 6.3+ with same code.
Description Resource Path Location Type The method
createParser(NamedXContentRegistry, DeprecationHandler, String) in the
type JsonXContent is not applicable for the arguments
(NamedXContentRegistry, String) test.java
The Compile Error has called out: your createParser miss a DeprecationHandler parameter.
So you should set the DeprecationHandler, for example:
JsonXContent.jsonXContent.createParser(NamedXContentRegistry.EMPTY,
LoggingDeprecationHandler.INSTANCE,
jsonObj.toString());

Fali to use getAppliedStereotype to get id and name of requirement

In Eclipse, Using Papyrus neon and Acceleo 3.7 for SysML 1.4 diagram, the getAppliedStereotype()returns null.
The modules are
[module generate('http://www.eclipse.org/uml2/5.0.0/UML',
'http://www.eclipse.org/papyrus/sysml/1.4/SysML',
'http://www.eclipse.org/papyrus/sysml/1.4/SysML/Blocks',
'http://www.eclipse.org/papyrus/sysml/1.4/SysML/Activities',
'http://www.eclipse.org/papyrus/sysml/1.4/SysML/Requirements',
'http://www.eclipse.org/papyrus/sysml/1.4/SysML/ModelElements')]
I have added the following code in the generate.java but still cannot work
Map<URI, URI> uriMap = resourceSet.getURIConverter().getURIMap();
// UML2 profiles
URI uri = URI.createURI("platform:/plugin/org.eclipse.uml2.uml.resources");
uriMap.put(URI.createURI(UMLResource.LIBRARIES_PATHMAP), uri.appendSegment("libraries").appendSegment(""));
uriMap.put(URI.createURI(UMLResource.METAMODELS_PATHMAP), uri.appendSegment("metamodels").appendSegment(""));
uriMap.put(URI.createURI(UMLResource.PROFILES_PATHMAP), uri.appendSegment("profiles").appendSegment(""));
// SysML profiles
uri = URI.createURI("platform:/plugin/org.eclipse.papyrus.sysml14");
uriMap.put(URI.createURI(SysMLResource.LIBRARIES_PATHMAP), uri.appendSegment("librairies").appendSegment(""));
uriMap.put(URI.createURI("pathmap://SysML14_PROFILES/"), uri.appendSegment("model").appendSegment(""));
The code like c.getAppliedStereotypes() returns null. I want to get the information of a requirement like the following code which returns nothing because of the getAppliedStereotype operation:
[for (re : uml::Class | uml::Class.allInstances()->select(cl : uml::Class | cl.getAppliedStereotype('SysML::Requirements::Requirement') <> null))]
--[re.name/]
Modellpfad : [re.qualifiedName/]
Id : [re.getValue(re.getAppliedStereotype('SysML::Requirements::Requirement'), 'id')/]
Text : [re.getValue(re.getAppliedStereotype('SysML::Requirements::Requirement'), 'text')/]
[/for]
Well, if none of your model elements have an applied stereotype, you will find no classes or objects. Thus, when you try to print the applied stereotype of all elements with an applied stereotype without first ensuring that the list is itself not null, you will fail.

How to migrate <dynamic> from ibatis to mybatis

I wish to change this from ibatis 2.0
UPDATE AccountData SET
StatisticAccountingUnits= <isNotNull property="statisticAccountingUnits">#statisticAccountingUnits#</isNotNull> <isNull property="statisticAccountingUnits">null</isNull>,
TotalStatisticDays= <isNotNull property="totalStatisticDays">#totalStatisticDays#</isNotNull> <isNull property="totalStatisticDays">null</isNull>,
<dynamic>
<isNotNull property="unitPrice" prepend=", ">UnitPrice = #unitPrice#</isNotNull>
<isNotNull property="settlementAnnexNumber" prepend=", ">SettlementAnnexNumber = #settlementAnnexNumber#</isNotNull>
</dynamic>
WHERE AccountDataID=#accountDataId#
to Mybatis version 3.2.7
You can look here - http://mybatis.github.io/mybatis-3/dynamic-sql.html
By the way, you don't need code like
<isNotNull property="statisticAccountingUnits">#statisticAccountingUnits#</isNotNull> <isNull property="statisticAccountingUnits">null</isNull>
use #{statisticAccountingUnits, jdbcType=NUMERIC}
http://mybatis.github.io/mybatis-3/sqlmap-xml.html#Parameters
The JDBC Type is required by JDBC for all nullable columns, if null is
passed as a value. You can investigate this yourself by reading the
JavaDocs for the PreparedStatement.setNull() method.

Errors when creating table using cassandra-jdbc-1.2.1 jar

I am having some difficulty creating a column family (table) in cassandra via the cassandra-jdbc driver.
The cql command works correctly in cqlsh, but doesn't when using cassandra jdbc. I suspect this is something to do with the way I have defined my connection string. Any help would be greatly helpful.
Let me try and explain what I have done.
I have created a keyspace using cqlsh with the following command
CREATE KEYSPACE authdb WITH
REPLICATION = {
'class' : 'SimpleStrategy',
'replication_factor' : 1
};
This is as per the documentation at: http://www.datastax.com/docs/1.2/cql_cli/cql/CREATE_KEYSPACE#cql-create-keyspace
I am able to create a table (column family) in cqlsh using
CREATE TABLE authdb.users(
user_name varchar PRIMARY KEY,
password varchar,
gender varchar,
session_token varchar,
birth_year bigint
);
This works correctly.
My problems start when I try to create the table using cassandra-jdbc-1.2.1.jar
The code I use is:
public static void createColumnFamily() {
try {
Class.forName("org.apache.cassandra.cql.jdbc.CassandraDriver");
Connection con = DriverManager.getConnection("jdbc:cassandra://localhost:9160/authdb?version=3.0.0");
String qry = "CREATE TABLE authdb.users(" +
"user_name varchar PRIMARY KEY," +
"password varchar," +
"gender varchar," +
"session_token varchar," +
"birth_year bigint" +
")";
Statement smt = con.createStatement();
smt.executeUpdate(qry);
con.close();
} catch (Exception e) {
e.printStackTrace();
}
When using cassandra-jdbc-1.2.1.jar I get the following error:
main DEBUG jdbc.CassandraDriver - Final Properties to Connection: {cqlVersion=3.0.0, portNumber=9160, databaseName=authdb, serverName=localhost}
main DEBUG jdbc.CassandraConnection - Connected to localhost:9160 in Cluster 'authdb' using Keyspace 'Test Cluster' and CQL version '3.0.0'
Exception in thread "main" java.lang.NoSuchMethodError: org.apache.cassandra.thrift.Cassandra$Client.execute_cql3_query(Ljava/nio/ByteBuffer;Lorg/apache/cassandra/thrift/Compression;Lorg/apache/cassandra/thrift/ConsistencyLevel;)Lorg/apache/cassandra/thrift/CqlResult;
at org.apache.cassandra.cql.jdbc.CassandraConnection.execute(CassandraConnection.java:447)
Note: the cluster and key space are not correct
When using cassandra-jdbc-1.1.2.jar I get the following error:
main DEBUG jdbc.CassandraDriver - Final Properties to Connection: {cqlVersion=3.0.0, portNumber=9160, databaseName=authdb, serverName=localhost}
main INFO jdbc.CassandraConnection - Connected to localhost:9160 using Keyspace authdb and CQL version 3.0.0
java.sql.SQLSyntaxErrorException: Cannot execute/prepare CQL2 statement since the CQL has been set to CQL3(This might mean your client hasn't been upgraded correctly to use the new CQL3 methods introduced in Cassandra 1.2+).
Note: in this instance the cluster and keyspace appear to be correct.
The error when using the 1.2.1 jar is because you have an old version of the cassandra-thrift jar. You need to keep that in sync with the cassandra-jdbc version. The cassandra-thrift jar is in the lib directory of the binary download.

Resources