I need to use this request in java using mongodb driver
db.product.update({"orders._id":ObjectId("59328d583c5179156cb9c241")},
{
$set:{
"orders.$.description":"ccc"
}
})
my object
{
"_id" : ObjectId("59328d543c5179156cb9c240"),
"fullName" : "aaa",
"orders" : [
{
"_id" : ObjectId("59328d583c5179156cb9c241"),
"description" : "bbb"
}
]
}
Result
{
"_id" : ObjectId("59328d543c5179156cb9c240"),
"fullName" : "aaa",
"orders" : [
{
"_id" : ObjectId("59328d583c5179156cb9c241"),
"description" : "ccc"
}
] }
what i have tried
BasicDBObject set = new BasicDBObject("$set", new BasicDBObject("orders._id", myId));
set.append("$set", new BasicDBObject("description", "ccc");
product.update(searchQueryByOrderId, set);
driver used :
https://mvnrepository.com/artifact/org.mongodb/mongo-java-driver
Related
I'm trying to learn MongoDB and I want to get a String inside an Object Array, my MongoDB document is here:
{
"_id" : ObjectId("5f1507fed91e81246c409a59"),
"identification" : "punishment",
"lastID" : 2,
"punishmentsTypes" : [
{
"category" : "OFENSA_JOGADOR",
"reason" : "Ofensa a Jogador",
"group" : [
"HELPER",
"MODERATOR",
"ADMINISTRATOR",
"MANAGER",
"MASTER"
],
"description" : "Ofender algum jogador",
"cases" : [
{
"1" : {
"type" : "MUTE",
"duration" : 604800000
}
},
{
"2" : {
"type" : "BAN",
"duration" : 0
}
}
]
},
{
"category" : "FALSIFICACAO",
"reason" : "Falsificação de provas",
"group" : [
"ADMINISTRATOR",
"MANAGER",
"MASTER"
],
"description" : "Falsicar provas ao denunciar um jogador em nosso fórum",
"cases" : [
{
"1" : {
"type" : "BAN",
"duration" : 0
}
}
]
},
{
"category" : "HACK",
"reason" : "Hack",
"group" : [
"MODERATOR",
"ADMINISTRATOR",
"MANAGER",
"MASTER"
],
"description" : "Uso de cheats ou programas ilícitos",
"cases" : [
{
"1" : {
"type" : "BAN",
"duration" : 7776000000.0
}
},
{
"2" : {
"type" : "BAN",
"duration" : 0
}
}
]
}
],
"unpunishmentTypes" : [
{}
]
}
I've tried this:
MongoCollection<Document> collection = mongoDatabase.getCollection("settings");
BasicDBObject query = new BasicDBObject();
BasicDBObject field = new BasicDBObject();
query.put("id", "punish");
field.put("punishmentsTypes", 1);
field.put("_id", 0);
Document test = collection.find(query).projection(field).first();
assert test != null;
Object object = test.get("punishmentsTypes");
System.out.println(object);
And that's the output:
[Document{{category=OFENSA_JOGADOR}},
Document{{category=FALSIFICACAO}}, Document{{category=HACK}}]
How can I get only the category string, to the output be: OFENSA_JOGADOR, FALSIFICACAO, HACK?
I'm not sure how did you get that result with your query but here is how I get your result:
MongoCollection<Document> collection = mongoDatabase.getCollection("settings");
Document query = new Document();
query.put("identification", "punishment");
Document test = collection.find(query).first();
List<Document> punishmentsTypes = test.getList("punishmentsTypes", Document.class);
for (Document document : punishmentsTypes) {
String category = document.getString("category");
System.out.println(category);
}
I need to find the record/count where eventDetails.eventDelivery.stateCode = "Y-FINISH". It could be in any element in the array list.
Just want to find where stateCode = "Y-FINISH" present in the array list.
Sample Data #1:
{
"_id" : ObjectId("5a2fb09736cf07f6a1146691"),
"activityID" : "",
"eventDetails" : [
{
"eventDelivery" : {
"digital" : {
"secureid" : "1231321212"
},
"stateCode" : "X-FINISH",
"state" : "SUCCESS"
},
{
"eventDelivery" : {
"digital" : {
"secureid" : "8762871121"
},
"stateCode" : "Y-FINISH",
"state" : "SUCCESS"
}
],
}
Sample Data #2:
{
"_id" : ObjectId("5a2fb09736cf07f6a1146691"),
"activityID" : "",
"eventDetails" : [
{
"eventDelivery" : {
"digital" : {
"secureid" : "1231321212"
},
"stateCode" : "X-FINISH",
"state" : "SUCCESS"
},
{
"eventDelivery" : {
"digital" : {
"secureid" : "8762871121"
},
"stateCode" : "Y-FINISH",
"state" : "SUCCESS"
},
{
"eventDelivery" : {
"digital" : {
"secureid" : "7651327152
},
"stateCode" : "Z-FINISH",
"state" : "SUCCESS"
}
],
}
Need to read this using Java.
Using a 3.x version of the Mongo Java driver ...
MongoClient mongoClient = ...;
MongoCollection<Document> collection = mongoClient.getDatabase("...")
.getCollection("...");
Bson filter = Filters.eq("eventDetails.stateCode", "Y-FINISH");
long count = collection.count(filter);
I have a MongoDB collection of places. A typical place has most of the following fields:
{
"_id" : ObjectId("575014dc6b028f07bef53681"),
"_class" : "domain.model.PlaceV1",
"name" : "Γιασεμί",
"primary_photo_url" : "https://irs0.4sqi.net/img/general/original/34666238_STHSh6CHiC7hpAuB4rztRVg6cFc5ylfi15aRaR7zUuQ.jpg",
"seenDetails" : NumberLong(0),
"foursquare_checkins" : 646,
"foursquare_tips" : 28,
"keywords" : [
""
],
"verified" : 1,
"location" : {
"loc" : {
"type" : "Point",
"coordinates" : [
25.898318,
36.831486
]
},
"formattedAddress" : "Χώρα",
"locality" : "Amorgos",
"first_neighbourhood" : "Katapola",
"greek_locality" : "Αμοργός",
"greek_first_neighbourhood" : "Κατάπολα"
},
"contact" : {
"phone_numbers" : [
"+30 2285 074017"
]
},
"price" : {
"priceVotes" : NumberLong(0),
"price" : 0,
"priceVotesSum" : NumberLong(0)
},
"rating" : {
"rating" : 8,
"ratingVotes" : NumberLong(0),
"ratingVotesSum" : NumberLong(0)
},
"categories" : [
{
"cat_id" : NumberLong(10310061000),
"category" : "Café",
"greek_category" : "Καφετέρια",
"weight" : 4
},
{
"cat_id" : NumberLong(11610021000),
"category" : "Bar",
"greek_category" : "Μπαρ",
"weight" : 4
}
]
}
I want to make queries where the sorting will be based on a score that is a result of some expressions and conditions. From the mongo shell I have tried this:
db.place.aggregate([
{$match:{"location.locality":"Athens"}},
{$project:
{name:1, location:1, score:{
$let: {
vars:{ foursquare: {
$cond: { if: { $gte: [ "$foursquare_checkins", 500 ] }, then: 500, else: "$foursquare_checkins" }
},
rating: {$multiply:["$rating.rating", 100]},
},
in:{$add:["$$foursquare", "$$rating", "$seenDetails"]}
}
}
}
},
{$sort: {score: -1}}]).pretty();
This is a simple example of my queries. The score will contain more complex expressions like the distance from a location. The problem is that I cannot find a way to use the $let and the $cond operator in my Java code with Spring. Could anybody help?
You should be able to do this using nested DBObject and a Custom Aggregation Operation.
For Example:
Map operations = new HashMap();
operations.put("name", 1);
operations.put("location", 1);
operations.put("score", new BasicDBObject("$let", new BasicDBObject("vars", new BasicDBObject())));
Then you can create a CustomAggregationOperation to add this to your project
CustomAggregationOperation project = new CustomAggregationOperation(new BasicDBObject("$project", operation));
This will give you the following pipeline:
{ "$project" : { "score" : { "$let" : { "vars" : { }}} , "name" : 1 , "location" : 1}}
Then you can add your other stages:
Aggregation aggregate = Aggregation.newAggregation(match, project, sort);
public class CustomAggregationOperation implements AggregationOperation {
private DBObject operation;
public CustomAggregationOperation (DBObject operation) {
this.operation = operation;
}
#Override
public DBObject toDBObject(AggregationOperationContext context) {
return context.getMappedObject(operation);
}
}
I am new to MongoDB. I am trying to access nested doc in mongodb. My sample doc is
{
"Advertisement" : {
"html" : "zxcxz"
},
"Notification" : {
"date_from" : ISODate("2013-06-30T18:30:00Z"),
"date_too" : ISODate("2013-07-16T18:30:00Z"),
"description" : "vcvc",
"url" : "vcvc"
},
"_id" : ObjectId("51e4f10ee4b08e0a6ebcbe46"),
"group_name" : "sumit",
"target_audience" : {
"gender" : "male",
"section" : "xyz",
"catagory" : "--Computer--",
"location" : {
"country" : "--Country--",
"state" : "--State--",
"city" : "--City--"
}
}
}
I am trying to get gender from target_audience. My java code is
DBCursor f=con.coll.find(query);
while(f.hasNext())
{
f.next();
gender=(String) f.curr().get("target_audience.gender");
}
But it returns null.
The result of DBCursor.next() and DBCursor.curr() is a BasicDBObject. For keys with embedded documents, BasicDBObject.get(key) returns a BasicDBObject
DBCursor f=con.coll.find(query);
while(f.hasNext())
{
BasicDBObject result = (BasicDBObject) f.next();
BasicDBObject target = (BasicDBObject) result.get("target_audience");
gender = (String) target.get("gender");
}
Today I try to $set a DBRef with $db to collection.
But server say: "not okForStorage" , so operation is failed.
ps. my mongod version is 2.2
{
"ts" : ISODate("2013-01-16T14:05:42.814Z"),
"op" : "update",
"ns" : "mydb.coll1",
"query" : {
"_id" : NumberLong("928686353793211381")
},
"updateobj" : {
"$set" : {
"ref" : {
"$db" : "db2",
"$ref" : "coll2",
"$id" : NumberLong("928686353793211381")
}
}
},
"nscanned" : 1,
"keyUpdates" : 0,
"numYield" : 0,
"lockStats" : {
"timeLockedMicros" : {
"r" : NumberLong(0),
"w" : NumberLong(200)
},
"timeAcquiringMicros" : {
"r" : NumberLong(0),
"w" : NumberLong(5)
}
},
"exception" : "not okForStorage",
"exceptionCode" : 12527,
"millis" : 0,
"client" : "10.168.89.9",
"user" : ""
}
According to the docs, the order of the fields in the DBRef matters; so you'd need to reorder your ref object as:
"ref" : {
"$ref" : "coll2",
"$id" : NumberLong("928686353793211381"),
"$db" : "db2"
}