Spring MongoDB BasicQuery not working with projection - spring

I have following BasicQuery
BasicQuery query2 = new BasicQuery("{status:{$in:['APPROVED','NEW','OPEN']}},{siteId:1,_id:0}");
Where BasicQuery is a class from SpringData mongoDb org.springframework.data.mongodb.core.query.BasicQuery. While doing the debug the above query get compiled into
Query: { "status" : { "$in" : [ "APPROVED" , "NEW" , "OPEN"]}}, Fields: null, Sort: { }
But it should have been compiled as below
Query: { "status" : { "$in" : [ "APPROVED" , "OPEN" , "NEW"]}}, Fields: { "siteId" : 1 , "_id" : 0}, Sort: null
If you notice, fields are still missing into compiled BasicQuery. Please help how i can have project in BasicQuery. I can have projection by using Query as below.
Query query = new Query();
query.addCriteria(Criteria.where(STATUS).in(validStatus));
query.fields().include("siteId").exclude("_id");
My query is how i can achieve the same using BasicQuery.

I guess i got the answer. Instead of using single string argument constructor of BasicQuery we need to use two String argument basic query as follow.
BasicQuery query2 = new BasicQuery("{status:{$in:['APPROVED','NEW','OPEN']}}","{siteId:1,_id:0}");
Above will compile into following query
Query: { "status" : { "$in" : [ "APPROVED" , "OPEN" , "NEW"]}}, Fields: { "siteId" : 1 , "_id" : 0}, Sort: null

BasicQuery query = new BasicQuery("{ $and: [{ studentId: { $in: "+studentIds+" } }, { status: { $ne: '"+studStatus+"'} }] }");
studentIds is an array and studStatus is a string!
Thanks to vashishth

Related

Spring MongoDB : querying documents with two equal fields

I want to query that returns document that two fields of it are equal
I found mongodb raw query from this question :
db.coll.find({ $where : "this.field1 == this.field2" } );
How can I perform it with spring criteria:
criteria = criteria.andOperator(
Criteria.where("successfulSent").is("true"),
Criteria.where("this.fieldOne == this.fieldTwo"));
but its not working beacuse generated query become :
{ ... "$and" : [ { "successfulSent" : "true"} , { "this.fieldOne == this.fieldOne " : { }}]}
You can try on this way:
Criteria.where("$where").is("this.field1 == this.field2")
Query toString() will be:
Query: { "$where" : "this.cts == this.uts"}, Fields: null, Sort: null

Spring Data mongodb: 'year' must evaluate to an integer

I've built this aggregation:
ProjectionOperation projectStage = Aggregation
.project("application", "uploadedRefs", "uploadedKb", "downloadedDocs", "downloadedKb")
.and(DateOperators.Year.yearOf("timestamp")).as("year")
.and(DateOperators.Month.monthOf("timestamp")).as("month")
.and(DateOperators.DayOfMonth.dayOfMonth("timestamp")).as("day")
.and(DateOperators.DateFromParts.dateFromParts()
.yearOf("timestamp")
.monthOf("timestamp")
.dayOf("timestamp")
).as("startIntervalTimestamp");
Aggregation aggregation = Aggregation
.newAggregation(
projectStage
);
System.out.println(aggregation.toString());
The output is:
[
{
"$project":{
"application":1,
"uploadedRefs":1,
"uploadedKb":1,
"downloadedDocs":1,
"downloadedKb":1,
"year":{
"$year":"$timestamp"
},
"month":{
"$month":"$timestamp"
},
"day":{
"$dayOfMonth":"$timestamp"
},
"startIntervalTimestamp":{
"$dateFromParts":{
"year":"timestamp",
"month":"timestamp",
"day":"timestamp"
}
}
}
}
]
The error message is:
Error: command failed: {
"ok" : 0,
"errmsg" : "'year' must evaluate to an integer, found string with value \"timestamp\"",
"code" : 40515,
"codeName" : "Location40515"
}
Solved:
Field timestampField = Fields.field("timestamp");
ProjectionOperation projectStage = Aggregation
.project("application", "uploadedRefs", "uploadedKb", "downloadedDocs", "downloadedKb")
.and(DateOperators.Year.year(timestampField)).as("year")
.and(DateOperators.Month.month(timestampField)).as("month")
.and(DateOperators.DayOfMonth.dayOfMonth(timestampField)).as("day")
.and(DateOperators.DateFromParts.dateFromParts()
.year(DateOperators.Year.year(timestampField))
.month(DateOperators.Month.month(timestampField))
.day(DateOperators.DayOfMonth.dayOfMonth(timestampField))
).as("startIntervalTimestamp");

missing type in composite literal in golang/mongodb aggregate query

I want to write mongo query in golang. my mongo query is -
aggregate([
{$match: {$and :
[
{"stream" : "CS"},
{"semester" : "sem3"},
{"section" : "A"}
]
}},
{$unwind: '$atndnc'},
{ $group: { _id:{rollno: "$atndnc.rollno",attend:"$atndnc.attend"},count: { $sum: 1 }}},
{ $project:
{ _id: '$_id.rollno',
'attend' : '$_id.attend',
'count' : '$count'
}}
])
And my Go code is -
cond:=[]bson.M{
bson.M{"$match": bson.M{"$and ":[]interface{}{
bson.M{"stream" : srchobj.Stream},
bson.M{"semester" : srchobj.Semester},
bson.M{"section" : srchobj.Section},
bson.M{"college_id":srchobj.College_id},
bson.M{"date":bson.M{"$gt":srchobj.Startdate,"$lt":srchobj.Enddate}}}}},
bson.M{"$unwind": "$atndnc"},
bson.M{"$group":bson.M{"_id":{"rollno":bson.M{"$atndnc.rollno"},"attend":bson.M{"$atndnc.attend"}},"count":bson.M{"$sum":1}}},
bson.M{"$project":bson.M{"_id":"$_id.rollno","count":"$_id.count"}}}
but it give the error "missing type in composite literal" in
bson.M{"$group":bson.M{"_id":{"rollno":bson.M{"$atndnc.rollno"},"attend":bson.M{"$atndnc.attend"}},"count":bson.M{"$sum":1}}},
in this line.what should i do now?
You have a missing type declaration on a set of braces in your $group query:
{"rollno":bson.M{"$atndnc.rollno"},"attend":bson.M{"$atndnc.attend"}}
I would assume should be:
bson.M{"rollno":bson.M{"$atndnc.rollno"},"attend":bson.M{"$atndnc.attend":nil}}
there are also a few other initialization things like initializations with just a string key (remember, a bson.M is just an alias for map[string]interface{}
Thanks for your support.I got the desired output by doing this.
cond :=[]bson.M{
bson.M{"$match": bson.M{
"stream" : srchobj.Stream,
"semester" : srchobj.Semester,
"section" : srchobj.Section,
"college_id":srchobj.College_id,
"date":bson.M{
"$gt":srchobj.Startdate,
"$lt":srchobj.Enddate},
},
},
bson.M{"$unwind": "$atndnc"},
bson.M{"$group":bson.M{
"_id":bson.M{
"rollno":"$atndnc.rollno",
"attend":"$atndnc.attend",
"name":"$atndnc.name",
},
"count":bson.M{"$sum":1},
},
},
bson.M{"$project":bson.M{
"rollno":"$_id.rollno",
"name":"$_id.name",
"count":"$count",
"attend":"$_id.attend",
},
},
bson.M{"$sort":bson.M{"rollno":1}},
}

how to use mongodb query option in monk nodejs

I have a collection name projects and I am trying to retrieve everything except its url like this query
db.projects.find({name:"arisha"},{url:0}).pretty()
This query is working perfectly and returning everything except url but my question is how to achieve this in
Node module for MongoDB name monk.
I am using this code but its not working and returning every field:
var projs = db.get('projects');
projs.find({creator : req.session.user._id},{url:0}, function (err,data) {
console.log(data);
if(!err) {
res.locals.projs = data;
console.log(data);
res.render("projects.ejs",{title: "Projects | Bridge"});
}
});
I did not get where the problem is, please help and thanks in advance :)
Sample document:
{
"name" : "arisha",
"date" : {
"day" : 18,
"month" : 4,
"year" : 2015
},
"creator" : "552edb6f8617322203701ad1",
"url" : "EyjPdYoW",
"members" : [
"552edb6f8617322203701ad1"
],
"_id" : ObjectId("5532994ba8ffdca31258bd1a")
}
To exclude the url field in monk, try the following syntax:
var db = require('monk')('localhost/mydb');
var projs = db.get('projects');
projs.find({ creator : req.session.user._id }, "-url", function (err, data) {
// exclude url field
});
EDIT:
To exclude multiple fields, use the following projection syntax:
projs.find({ creator : req.session.user._id }, { fields: { url: 0, creator: 0 } }, function(err, data) {
// exclude the fields url and creator
});
Alternatively (as you had discovered), you could also do:
projs.find({ creator : req.session.user._id }, "-url -creator", function (err, data) {
// exclude url and creator fields
});

update in a nested array using C# Driver in MongoDB

Here is my exact schema:
{
"_id" : ObjectId("4fb4fd04b748611ca8da0d45"),
"Name" : "Agent name",
"City" : "XXXX",
"BranchOffice" : [{
"_id" : ObjectId("4fb4fd04b748611ca8da0d46"),
"Name" : "Branch name",
"City" : "XXXX",
"SubBranch" : [{
"_id" : ObjectId("4fb4fd04b748611ca8da0d47"),
"Name" : "Sub-Branch Name",
"City" : "XXXX"
"Users" : [{
"_id" : ObjectId("4fb4fd04b748611ca8da0d48"),
"Name" : "User",
"City" : "XXXX"
}]
}]
}]
}
Its Inserted successfully in c#. insert code was below but update condition is failed .
I want to update field 3 level and 4 level of array using SubBranch and users
Insert code
IMongoQuery query = Query.And(Query.EQ("_id", new ObjectId(4fb4fd04b748611ca8da0d45)),
Query.EQ("BranchOffice._id", new ObjectId(4fb4fd04b748611ca8da0d46)));
Agent agent = dc.Collection.FindOne(query);
BsonDocument branchOffice = agent.BranchOffice.Find(objId => objId._id == new ObjectId(4fb4fd04b748611ca8da0d46)).ToBsonDocument();
subBranch I had get List object convert to BsonDocument
Files: name,city,_Id, and users for array
BsonDocument subBranchOffice = **subBranch.ToBsonDocument()**;
if (branchOffice.Contains("SubBranch"))
{
if (branchOffice["SubBranch"].IsBsonNull)
{
branchOffice["SubBranch"] = new BsonArray().Add(BsonValue.Create(subBranchOffice));
}
else
{
branchOffice["SubBranch"].AsBsonArray.Add(BsonValue.Create(subBranchOffice));
}
var update = Update.Set("BranchOffice.$.SubBranch",branchOffice["SubBranch"]);
SafeModeResult s = dc.Collection.Update(query, update, UpdateFlags.Upsert,SafeMode.True);
}
Here SafemodeResult is UpdateExisting = true
Here Inserted Option is successfully
next I try to update in else Statement. I am not get it answer
Update code
else
{
var queryEdit = Query.And(Query.EQ("_id", new ObjectId(4fb4fd04b748611ca8da0d45)),
Query.EQ("BranchOffice._id", new ObjectId(4fb4fd04b748611ca8da0d46)),
Query.EQ("SubBranchlist._id", new ObjectId(4fb4fd04b748611ca8da0d47)));
**//Index value 1 or 2 or 3**
var update = Update.Set("BranchOffice.$.SubBranch."index value".Name", "sname").
Set("BranchOffice.$.SubBranch."index value".city", "yyyyy" ?? string.Empty);
SafeModeResult s = dc.Collection.Update(queryEdit, update, UpdateFlags.None,SafeMode.True);
}
Here SafemodeResult is UpdateExisting = False
Here updated Option is fail
Please explain how to solve this probelm and how to update field 2 and 3 level of array
Please show any Example
There's a lot there, but it looks like at least part of your problem is that you've spelled BranchOffice differently between the data and the query you are using to update, also you've missed the hierarchy in SubBranch, so your queryEdit in the last code sample won't match the document. This will;
db.so.find({
_id: ObjectId("4fb4fd04b748611ca8da0d45"),
"BrancheOffice._id": ObjectId("4fb4fd04b748611ca8da0d46"),
"BrancheOffice.SubBranch._id": ObjectId("4fb4fd04b748611ca8da0d47"),
}).toArray()

Resources