And Operator in Criteria not working as expected for nested documents inside aggregation Spring Data Mongo - mongodb

I am trying to fetch total replies where read values for a replies is true. But I am getting count value as 3 but expected value is 2 (since only two read value is true) through Aggregation function available in Spring Data Mongo. Below is the code which I wrote:
Aggregation sumOfRepliesAgg = newAggregation(match(new Criteria().andOperator(Criteria.where("replies.repliedUserId").is(userProfileId),Criteria.where("replies.read").is(true))),
unwind("replies"), group("replies").count().as("repliesCount"),project("repliesCount"));
AggregationResults<Comments> totalRepliesCount = mongoOps.aggregate(sumOfRepliesAgg, "COMMENTS",Comments.class);
return totalRepliesCount.getMappedResults().size();
Using AND Operator inside Criteria Query and passed two criteria condition but not working as expected. Below is the sample data set:
{
"_id" : ObjectId("5c4ca7c94807e220ac5f7ec2"),
"_class" : "com.forum.api.domain.Comments",
"comment_data" : "logged by karthe99",
"totalReplies" : 2,
"replies" : [
{
"_id" : "b33a429f-b201-449b-962b-d589b7979cf0",
"content" : "dasdsa",
"createdDate" : ISODate("2019-01-26T18:33:10.674Z"),
"repliedToUser" : "#karthe99",
"repliedUserId" : "5bbc305950a1051dac1b1c96",
"read" : false
},
{
"_id" : "b886f8da-2643-4eca-9d8a-53f90777f492",
"content" : "dasda",
"createdDate" : ISODate("2019-01-26T18:33:15.461Z"),
"repliedToUser" : "#karthe50",
"repliedUserId" : "5c4bd8914807e208b8a4212b",
"read" : true
},
{
"_id" : "b56hy4rt-2343-8tgr-988a-c4f90598h492",
"content" : "dasda",
"createdDate" : ISODate("2019-01-26T18:33:15.461Z"),
"repliedToUser" : "#karthe50",
"repliedUserId" : "5c4bd8914807e208b8a4212b",
"read" : true
}
],
"last_modified_by" : "karthe99",
"last_modified_date" : ISODate("2019-01-26T18:32:41.394Z")
}
What is the mistake in the query that I wrote?

Related

Mongodb put Documents array as the same level

I have this array of documents, I would like to put "table" on the same level like mastil_antenas and other variables. how Can I do that with aggregate?
I'm trying with the aggregate $project but I can't get the result.
Example of Data
[ {
"mastil_antena" : "1",
"nro_platf" : "1",
"antmarcmast" : "ANDREW",
"antmodelmast" : "HWXXX6516DSA3M",
"retmarcmast" : "Ericsson",
"retmodelmast" : "ATM200-A20",
"distmast" : "1.50",
"altncramast" : "41.30",
"ORIENTMAG" : "73.00",
"incelecmast" : "RET",
"incmecmast" : "1.00",
"Feedertypemast" : "Fibra Optica",
"longjumpmast" : "5.00",
"longfo" : "100",
"calibrecablefuerza" : "10 mm",
"longcablefuerza" : "65.00",
"modelorruantena" : "32B66A",
"tiltmecfoto" : "https://secure.appenate.com/Files/FormEntry/47929-92cdf219-3128-4903-8324-a81000602b9d171017114934746000.jpg",
"tiltmecfoto_fh" : "2017-10-18T05:51:22Z",
"az0foto" : "https://secure.appenate.com/Files/FormEntry/47929-92cdf219-3128-4903-8324-a81000602b9d171017115012727000.jpg",
"az0foto_fh" : "2017-10-18T05:55:21Z",
"azneg60foto" : "https://secure.appenate.com/Files/FormEntry/47929-92cdf219-3128-4903-8324-a81000602b9d171017115016199000.jpg",
"azneg60foto_fh" : "2017-10-18T05:55:36Z",
"azpos60foto" : "https://secure.appenate.com/Files/FormEntry/47929-92cdf219-3128-4903-8324-a81000602b9d171017115020147000.jpg",
"azpos60foto_fh" : "2017-10-18T05:55:49Z",
"etiqantenafoto" : "https://secure.appenate.com/Files/FormEntry/47929-92cdf219-3128-4903-8324-a81000602b9d171017114920853000.jpg",
"etiqantenafoto_fh" : "2017-10-18T05:56:01Z",
"tiltelectfoto" : "https://secure.appenate.com/Files/FormEntry/47929-92cdf219-3128-4903-8324-a81000602b9d171017114914236000.jpg",
"tiltelectfoto_fh" : "2017-10-18T05:56:13Z",
"idcablefoto" : "https://secure.appenate.com/Files/FormEntry/47929-92cdf219-3128-4903-8324-a81000602b9d171017114900279000.jpg",
"idcablefoto_fh" : "2017-10-18T05:56:38Z",
"rrutmafoto" : "https://secure.appenate.com/Files/FormEntry/47929-92cdf219-3128-4903-8324-a81000602b9d171017114947279000.jpg",
"rrutmafoto_fh" : "2017-10-18T05:56:49Z",
"etiquetarrufoto" : "https://secure.appenate.com/Files/FormEntry/47929-92cdf219-3128-4903-8324-a81000602b9d171017114954648000.jpg",
"etiquetarrufoto_fh" : "2017-10-18T05:57:02Z",
"rrutmafoto1" : "https://secure.appenate.com/Files/FormEntry/47929-92cdf219-3128-4903-8324-a81000602b9d171017114959738000.jpg",
"rrutmafoto1_fh" : "2017-10-18T05:57:12Z",
"etiquetarrufoto1" : "https://secure.appenate.com/Files/FormEntry/47929-92cdf219-3128-4903-8324-a81000602b9d171017115005545000.jpg",
"etiquetarrufoto1_fh" : "2017-10-18T05:57:27Z",
"botontorre4" : "sstelcel3",
"table" : { /* put all varibles one level up*/
"tecmast" : "LTE",
"frecmast" : "2100",
"secmast" : "1",
"untitled440" : "Salir"
},
"comentmast" : "",
"longfeedmast" : "",
"numtmasmast" : "",
"otra_marca_antena" : "",
"otro_modelo_antena" : ""
}]
Starting from MongoDB version 3.4 you could use $addFields to do this.
//replace products with what makes sense in your database
db.getCollection('products').aggregate(
[
{ //1 add the properties from subdocument table to documents
$addFields: {
"documents.tecmast" : "documents.0.table.tecmast",
"documents.frecmast" : "documents.0.table.frecmast",
"documents.secmast" : "documents.0.table.secmast",
"documents.untitled440" : "documents.0.table.untitled440"
}
},
{
//(optional) 2 remove the table property from the documents
$project: {"documents.table" : 0}
}
]
)
Step 1: use $addFields to grab properties from table inside documents.table and put them on documents
Step 2: (optional) remove property "table" from documents.
I hope this helps!!!

How to find something from an array in mongo

{
"_id" : ObjectId("586aac4c8231ee0b98458045"),
"store_code" : NumberInt(10800),
"counter_name" : "R.N.Electric",
"address" : "314 khatipura road",
"locality" : "Khatipura Road (Jhotwara)",
"pincode" : NumberInt(302012),
"town" : "JAIPUR",
"gtm_city" : "JAIPUR",
"sales_office" : "URAJ",
"owner_name" : "Rajeev",
"owner_mobile" : "9828024073",
"division_mapping" : [//this contains only 1 element in every doc
{
"dvcode" : "cfc",
"dc" : "trade",
"beatcode" : "govindpura",
"fos" : {
"_id" : ObjectId("586ab8318231ee0b98458843"),
"loginid" : "9928483483",
"name" : "Arpit Gupta",
"division" : [
"cfc",
"iron"
],
"sales_office" : "URAJ", //office
"gtm_city" : "JAIPUR" //city
},
"beat" : {
"_id" : ObjectId("586d372b39f64316b9c3cbd7"),
"division" : {
"_id" : ObjectId("5869f8b639f6430fe4edee2a"),
"clientdvcode" : NumberInt(40),
"code" : "cfc",
"name" : "Cooking & Fabric Care",
"project_code" : "usha-fos",
"client_code" : "usha",
"agent_code" : "v5global"
},
"beatcode" : "govindpura",
"sales_office" : "URAJ",
"gtm_city" : "JAIPUR",
"active" : true,
"agency_code" : "v5global",
"client_code" : "USHA_FOS",
"proj_code" : "usha-fos",
"fos" : {
"_id" : ObjectId("586ab8318231ee0b98458843"),
"loginid" : "9928483483",
"name" : "Arpit Gupta",
"division" : [
"cfc",
"iron"
],
"sales_office" : "URAJ",
"gtm_city" : "JAIPUR"
}
}
}
],
"distributor_mail" : "sunil.todi#yahoo.in",
"project_code" : "usha-fos",
"client_code" : "usha",
"agent_code" : "v5global",
"distributor_name" : "Sundeep Electrical"
}
I am having only 1 element in division_mapping's array and I want to find those documents whose dc in division_mapping is trade.
I have tried following:
"division_mapping":{$elemMatch:{$eq:{"dc":"trade"}}}})
Dont know what I am doing wrong.
//Maybe I have to unwind the array but is there any other way?
According to MongoDB documentation
The $elemMatch operator matches documents that contain an array
field with at least one element that matches all the specified query
criteria.
According to above mentioned description to retrieve only documents whose dc in division_mapping is trade please try executing below mentioned query
db.collection.find({division_mapping:{$elemMatch:{dc:'trade'}}})

$nin operator doesn't work correctly

When I use this method, I get all documents from _User collection. (as expected)
db.getCollection("_User").find({ "_id" : { $nin: [] }})
However, when I add at least one string to $nin array:
db.getCollection("_User").find({ "_id" : { $nin: ["7HpHbmF5iu","ga61t3afsa"] }})
I get empty results. (expected - to get all documents without the ones with ids 7HpHbmF5iu and ga61t3afsa)
MongoDB version 3.2.6
These are two documents I want to filter from all:
{ "_id" : "7HpHbmF5iu", "expiration_date" : ISODate("2015-12-28T08:51:21.252Z"), "_created_at" : ISODate("2015-10-29T08:51:23.302Z"), "_updated_at" : ISODate("2016-03-10T17:37:45.262Z"), "gender" : "female", "firstName" : "Toma", "verification" : "verified", "birthdayDate" : ISODate("1995-02-15T00:00:00Z") }
{ "_id" : "ga61t3afsa", "expiration_date" : ISODate("2015-12-27T07:54:21.235Z"), "_created_at" : ISODate("2015-10-28T07:11:22.102Z"), "_updated_at" : ISODate("2016-03-11T16:11:10.100Z"), "gender" : "female", "firstName" : "Goda", "verification" : "verified", "birthdayDate" : ISODate("1992-09-13T00:00:00Z") }
It was an error in Azure DocumentDB with Mongo, however I've chosen not to use their services, so I don't know if they've already fixed it.

How to query an array of objects in mongodb

I have an object structure as shown below
{
"_id" : ObjectId("55d164f1c8f2c53a82535b9a"),
"plant_name" : "TOTAL",
"installed_capacity" : 3473,
"wind_data" : [
{
"date" : "16-08-15",
"timestamp" : " 16:27:15",
"generated_capacity" : 617.24,
"frequency" : 50.01
},
{
"date" : "16-08-15",
"timestamp" : " 21:21:15",
"generated_capacity" : 670.25,
"frequency" : 49.94
}, ....]
}
I need to sum up (at least retrieve) "generated_capacity" of all the objects under "wind_data" having "date" equal to "16-08-15" of "TOTAL" object. I have tried this query
db.collectionName.aggregate(
{"$unwind":"$wind_data"},
{"$match":{"plant_name":"TOTAL","wind_data.date":"16-08-15"}}
)
But, this query is not working. Please suggest some way to figure this out.
The following query would do the job
db.collectionName.aggregate([
{"$unwind":"$wind_data"},
{"$match":{"plant_name":"TOTAL","wind_data.date":"16-08-15"}},
{"$group":{"_id":"$wind_data.date","generated_capacity_sum":{"$sum":"$wind_data.generated_capacity"}}}
])

How to run multi condition check in mongodb update query?

I have the following scenario.
I need to check multiple condition in a single update query.
Sample Data :
"host" : "zigwheels.com",
"lastAccessDate" : "20140819",
"sessionId" : "ff8378ed-ccda-4a75-b24b-4a4bb1153e39"
Here is my requirement :
obj=db.userFrequency.find({"host" : "xyz.com", "sessionId" : "ff8378ed-ccda-4a75-b24b-4a4bb1153e39"});
if(obj!=null){
if(obj.get("lastAccessDate")!= todayDate){
//If page has not visited today, increment count by 1 and update "lastAccessDate"=todayDate
db.userFrequency.update({"host" : "xyz.com","sessionId" : "ff8378ed-ccda-4a75-b24b-4a4bb1153e39"},{$set : {"lastAccessDate"=todayDate},$inc : {"count":1}});
}
else{
// If page visited today{lastAccessDate==todayDate}, no need to update count
}
}else{
//Insert the new Entry
db.userFrequency.update({"host" : "xyz.com","sessionId" : "ff8378ed-ccda-4a75-b24b-4a4bb1153e39"},{$set : {"lastAccessDate"=todayDate},$inc : {"count":1}},{upsert:true});
}
I need to do the above operation in a single query but I have GB's of data.
I tried above like below :
db.userFrequency.update({"host" : "xyz.com","lastAccessDate"!=todayDate,"sessionId" : "ff8378ed-ccda-4a75-b24b-4a4bb1153e39"},{$set : {"lastAccessDate"=todayDate},$inc : {"count":1}});
but it inserts new entry because the above condition requires three checks.
Please suggest a solution for the same.
It's awkward if you store your date as a string. Store dates as date type fields and this is easy:
> db.userFrequency.insert({
"host" : "zigwheels.com",
"lastAccessDate" : ISODate("2014-08-19"),
"sessionId" : "ff8378ed-ccda-4a75-b24b-4a4bb1153e39"
})
> var today = ISODate("2014-08-25")
> db.userFrequency.update({
"host" : "zigwheels.com",
"lastAccessDate" : { "$lt" : today },
"sessionId" : "ff8378ed-ccda-4a75-b24b-4a4bb1153e39"
},
{
$set : { "lastAccessDate" : today},
$inc : { "count" : 1 }
})
> db.userFrequency.findOne()
{
"_id" : ObjectId("53fbd08...398"),
"host" : "zigwheels.com",
"lastAccessDate" : ISODate("2014-08-25T00:00:00Z"),
"sessionId" : "ff8378ed-ccda-4a75-b24b-4a4bb1153e39",
"count" : 1
}
I used the $lt operator for the date test because users won't access the website from the future...hopefully. Using proper dates also surfaces another important issue- what timezone defines today? Right now, for me, it's tomorrow in Australia...