So let’s say I have a patient document in MongoDB. It has things such as first name, last name, etc… I am trying to add to the current document a list of providers (which is another collection, by DBRef, as I am using POJO. How would I append multiple providers in Java to the document?
One way to do this is by just appending to a document like this:
Document doc = new Document("user", userObject)
.append("providers", providersObject);
providersObject would be your list of providers.
Related
I am parsing tables using jsoup. I need to connect to division standing tables from this website: https://www.basketball-reference.com/leagues/NBA_2006.html. Don't know how to parse tables because I need to use the same method for every division standing table, but the id is different for older seasons (e.g. id="divs_standings_W", "id="divs_standings_E" and "id="divs_standings_"). Link to some older season: https://www.basketball-reference.com/leagues/NBA_1950.html.
How can I check if the table with the given id exists and if it exists put it in a variable table? Don't have much relevant code.
Document doc = Jsoup.connect("https://www.basketball-reference.com/leagues/NBA_1950.html").get();
Elements table = doc.select("table[id=\"divs_standings_\"]");
You can just use prefix matching. Use table[id^="divs_standings_"]. This will match all tables, with ids starting with divs_standings_:
Document doc = Jsoup.connect("https://www.basketball-reference.com/leagues/NBA_1950.html").get();
Element table = doc.selectFirst("table[id^=\"divs_standings_\"]");
This will work for old and new seasons.
To wrap this in a method you can just use something like this:
private static void processTable(String url) throws IOException {
Document doc = Jsoup.connect(url).get();
Element table = doc.selectFirst("table[id^=\"divs_standings_\"]");
System.out.println(table);
}
and call it with both urls:
processTable("https://www.basketball-reference.com/leagues/NBA_1950.html");
processTable("https://www.basketball-reference.com/leagues/NBA_2006.html");
You also can use pattern matching if you have more complex ids. Check out the link above for this.
How to query data from collection where document reference contain specific path?
Here is my Firestore database, filed user is a document reference type, mapped document reference form other collection.
Here I need to get all data from userinfo collection where user document reference contains specific path (eg : player/8SLuNWrI09UIuUfNe7ZR/playerinfo )
I have tried following query but seems not working:
Query query = mFirebaseFirestore.collection("userinfo").whereGreaterThanOrEqualTo("user", "player/8SLuNWrI09UIuUfNe7ZR/playerinfo");
Code to get data from query:
query.addSnapshotListener(new EventListener<QuerySnapshot>() {
#Override
public void onEvent(QuerySnapshot queryDocumentSnapshots, FirebaseFirestoreException e) {
//queried data here
}
});
No example available on document to query Firestore with document reference type.
Please help me to query list of document from collection where document reference having specific path.
Thanks in advance
You don't find any examples in the official documentation of Firestore because unfortunately, there is no contains() method which can help you verify if a String is apart of a reference, which is a property of a document.
However, if you want to get all document that exist under playerinfo collection, then just use a get() call. Don't use addSnapshotListener() unless you need to get data in real-time.
There is a solution in which you need to transform your user property to be of type String and use a query that look like this:
Query query = = mFirebaseFirestore.collection("userinfo").whereEqualTo("user", "player/8SLuNWrI09UIuUfNe7ZR/playerinfo");
But rememeber, this will work only if the property user holds a value of type String which is equal to:
player/8SLuNWrI09UIuUfNe7ZR/playerinfo`
and not:
player/8SLuNWrI09UIuUfNe7ZR/playerinfo/qY0D7Vef...
^ ^
There is one more in way in which you can solve this. Query the entire collection, get all the values of user property and add them to a List by converting them from Reference to String. In the end, just iterate over the list and use contains() method on each element.
You just want to get the document by its location in the database:
mFirebaseFirestore.collection("userinfo").document("8SLuNWrI09UIuUfNe7ZR").get()
No need for a query if you know the specific document to fetch.
I am using mongodb 3.4 and I want to get the last inserted document id. I have searched all and I found out below code can be used if I used a BasicDBObject.
BasicDBObject docs = new BasicDBObject(doc);
collection.insertOne(docs);
ID = (ObjectId)doc.get( "_id" );
But the problem is am using Document type not BasicDBObject so I tried to get it as like this, doc.getObjectId();. But it asks a parameter which I actually I want, So does anyone know how to get it?
EDIT
This is the I am inserting it to mongo db.
Document doc = new Document("jarFileName", jarDataObj.getJarFileName())
.append("directory", jarDataObj.getPathData())
.append("version", jarDataObj.getVersion())
.append("artifactID", jarDataObj.getArtifactId())
.append("groupID", jarDataObj.getGroupId());
If I use doc.toJson() it shows me whole document. is there a way to extract only _id?
This gives me only the value i want it like the objectkey, So I can use it as reference key.
collection.insertOne(doc);
jarID = doc.get( "_id" );
System.out.println(jarID); //59a4db1a6812d7430c3ef2a5
Based on ObjectId Javadoc, you can simply instantiate an ObjectId from a 24 byte Hex string, which is what 59a4db1a6812d7430c3ef2a5 is if you use UTF-8 encoding. Why don't you just do new ObjectId("59a4db1a6812d7430c3ef2a5"), or new ObjectId("59a4db1a6812d7430c3ef2a5".getBytes(StandardCharsets.UTF_8))? Although, I'd say that exposing ObjectId outside the layer that integrates with Mongo is a design flaw.
How can I find a document and retrieve it if found, but insert and retrieve it if not found in one command?
I have an outline for the formats I wish my documents to look like for a user's data. Here is what it looks like
{
"username": "HeyAwesomePeople",
"uuid": "0f91ede5-54ed-495c-aa8c-d87bf405d2bb",
"global": {},
"servers": {}
}
When a user first logs in, I want to store the first two values of data (username and uuid) and create those empty values (global and servers. Both those global and servers will later on have more information filled into them, but for now they can be blank). But I also don't want to override any data if it already exists for the user.
I would normally use the insertOne or updateOne calls to the collection and then use the upsert (new UpdateOptions().upsert(true)) option to insert if it isn't found but in this case I also need to retrieve the user's document aswell.
So in a case in which the user isn't found in the database, I need to insert the outlined data into the database and return the document saved. In a case where the user is found in the database, I need to just return the document from the database.
How would I go about doing this? I am using the latest version of Mongo which has deprecated the old BasicDBObject types, so I can't find many places online that use the new 'Document' type. Also, I am using the Async driver for java and would like to keep the calls to the minimum.
How can I find a document and retrieve it if found, but insert and retrieve it if not found in one command?
You can use findOneAndUpdate() method to find and update/upsert.
The MongoDB Java driver exposes the same method name findOneAndUpdate(). For example:
// Example callback method for Async
SingleResultCallback<Document> printDocument = new SingleResultCallback<Document>() {
#Override
public void onResult(final Document document, final Throwable t) {
System.out.println(document.toJson());
}
};
Document userdata = new Document("username","HeyAwesomePeople")
.append("uuid", "0f91ede5")
.append("global", new Document())
.append("servers", new Document());
collection.findOneAndUpdate(userdata,
new Document("$set", userdata),
new FindOneAndUpdateOptions()
.upsert(true)
.returnDocument(ReturnDocument.AFTER),
printDocument);
The query above will try to find a document matching userdata; if found set it to the same value as userdata. If not found, the upsert boolean flag will insert it into the collection. The returnDocument option is to return the document after the action is performed.
The upsert and returnDocument flags are part of FindOneAndUpdateOptions
See also MongoDB Async Java Driver v3.4 for tutorials/examples. The above snippet was tested with current version of MongoDB v3.4.x.
I recently changed a POJO from having all its typed properties to something free in a typed JSONObject field called content.
The problem is that all old documents map to the old POJO version, so they are stored like this:
{"_id":"ObjectId(value)","field1":"value1","field2":"value2"}
Can I update all fields via a single mongo command so I can wrap all the content, except the id, so the result would be something like this:
{"_id":"ObjectId(value)","content":{"field1":"value1","field2":"value2"}}
?
Or should I program a simple program that does it one by one? (as in iterating all values sort of manually adding the new content level)
Unfortunately, there are no MongoDB commands that will allow you to restructure a document in this way. You'll need to write a program to fetch all of your documents one by one, update the structure, and then send the updated structure back to MongoDB.
Often the best way to do this is to write the modified documents to a new collection, and then drop the old collection when you're done.
I solved it creating a .js file to execute via mongo shell.
mongo myDb fixresults.js
The file is as follows:
for( var c = db.results.find(); c.hasNext(); ) {
var full = c.next();
var anon = db.results.findOne({"_id":full._id},{"_id":0});
var n = {"_id":full._id,"content":anon};
db.results.temp.insert(n);
}
This will insert the transformed value into the .temp collection, which you can rename later to replace the original.