Get all the distinct users through mongodb aggregation - mongodb

I have an collection for messages something like below. Now i want to get all the distinct users to which ObjectId("57f55e4799aabf1c0565bc10") messages or receive message excluding itself (ObjectId("57f55e4799aabf1c0565bc10")). So how i can achieve it using aggregation.
/* 1 */
{
"_id" : ObjectId("57f55e0199aabf1c0565bc0e"),
"message" : "fghjfghj",
"to" : ObjectId("57f54e154df8d0193577889a"),
"from" : ObjectId("57f5522099aabf1c0565bbfe"),
"modifiedDate" : ISODate("2016-10-05T20:09:37.307Z"),
"createdDate" : ISODate("2016-10-05T20:09:37.307Z"),
"isDeleted" : false,
"status" : true,
"type" : "Message",
"__v" : 0
}
/* 2 */
{
"_id" : ObjectId("57f55e2d99aabf1c0565bc0f"),
"message" : "ghjkfhkg",
"to" : ObjectId("57f54e154df8d0193577889a"),
"from" : ObjectId("57f5522099aabf1c0565bbfe"),
"modifiedDate" : ISODate("2016-10-05T20:10:21.245Z"),
"createdDate" : ISODate("2016-10-05T20:10:21.245Z"),
"isDeleted" : false,
"status" : true,
"type" : "Message",
"__v" : 0
}
/* 3 */
{
"_id" : ObjectId("57f55e4799aabf1c0565bc10"),
"message" : "hgkgh",
"to" : ObjectId("57f54e154df8d0193577889a"),
"from" : ObjectId("57f5522099aabf1c0565bbfe"),
"modifiedDate" : ISODate("2016-10-05T20:10:47.614Z"),
"createdDate" : ISODate("2016-10-05T20:10:47.614Z"),
"isDeleted" : false,
"status" : true,
"type" : "Message",
"__v" : 0
}
/* 4 */
{
"_id" : ObjectId("57f55e7199aabf1c0565bc11"),
"message" : "cbjngcfj",
"to" : ObjectId("57f54e154df8d0193577889a"),
"from" : ObjectId("57f5522099aabf1c0565bbfe"),
"modifiedDate" : ISODate("2016-10-05T20:11:29.197Z"),
"createdDate" : ISODate("2016-10-05T20:11:29.197Z"),
"isDeleted" : false,
"status" : true,
"type" : "Message",
"__v" : 0
}
/* 5 */
{
"_id" : ObjectId("57f5801d94ef64d760275368"),
"message" : "cbjngcfj",
"from" : ObjectId("57f54e154df8d0193577889a"),
"to" : ObjectId("57f5522099aabf1c0565bbfe"),
"modifiedDate" : ISODate("2016-10-05T20:11:29.197Z"),
"createdDate" : ISODate("2016-10-05T20:11:29.197Z"),
"isDeleted" : false,
"status" : true,
"type" : "Message",
"__v" : 0
}
/* 6 */
{
"_id" : ObjectId("57f5865494ef64d76027536a"),
"message" : "hgkgh",
"to" : ObjectId("57f54e154df8d0193577889b"),
"from" : ObjectId("57f5522099aabf1c0565bbfe"),
"modifiedDate" : ISODate("2016-10-05T20:10:47.614Z"),
"createdDate" : ISODate("2016-10-05T20:10:47.614Z"),
"isDeleted" : false,
"status" : true,
"type" : "Message",
"__v" : 0
}
/* 7 */
{
"_id" : ObjectId("57f666de7d13f10b5aa53527"),
"message" : "Zsdfsdf",
"to" : ObjectId("57f54dd36df11022ac5d7769"),
"from" : ObjectId("57f54dd36df11022ac5d7769"),
"modifiedDate" : ISODate("2016-10-06T14:59:42.943Z"),
"createdDate" : ISODate("2016-10-06T14:59:42.943Z"),
"isDeleted" : false,
"status" : true,
"type" : "Message",
"__v" : 0
}
/* 8 */
{
"_id" : ObjectId("57f667397d13f10b5aa53528"),
"message" : "HIIIIIIIIIIIII",
"to" : ObjectId("57f54dd36df11022ac5d7769"),
"from" : ObjectId("57f54dd36df11022ac5d7769"),
"modifiedDate" : ISODate("2016-10-06T15:01:13.993Z"),
"createdDate" : ISODate("2016-10-06T15:01:13.993Z"),
"isDeleted" : false,
"status" : true,
"type" : "Message",
"__v" : 0
}
/* 9 */
{
"_id" : ObjectId("57f66972a533c40d67ebfab8"),
"message" : "gfjghk",
"to" : ObjectId("57f54e154df8d0193577889a"),
"from" : ObjectId("57f5522099aabf1c0565bbfe"),
"modifiedDate" : ISODate("2016-10-06T15:10:42.721Z"),
"createdDate" : ISODate("2016-10-06T15:10:42.721Z"),
"isDeleted" : false,
"status" : true,
"type" : "Message",
"__v" : 0
}
I have tried but didn't able to get the required result as below :
db.getCollection('conversations').aggregate([
{$match : {'type' : 'Message',
$or : [
{from : ObjectId("57f5522099aabf1c0565bbfe")},
{to : ObjectId("57f5522099aabf1c0565bbfe")}
]
}
},
{ $group: {_id : {"to" : "$to", 'from':"$from" }}},
]);
Expecting results like : -
[
ObjectId("57f54e154df8d0193577889a")
ObjectId("57f54e154df8d0193577889b")
]
Thanks for any suggestion.

You can use the $addToSet to add the senders and receivers to their respective sets(lists). Then you can use $setUnion to combine the sets. Then, you can use $setDifference to remove the current user.
db.getCollection('conversations').aggregate([
{$match : {'type' : 'Message',$or : [ {from : ObjectId("57f5522099aabf1c0565bbfe")},
{to : ObjectId("57f5522099aabf1c0565bbfe")}]}},
{ $group: {_id : null, from : {"$addToSet" : "$from"}, to : {"$addToSet" : "$to"}}},
{"$project":{"userAll":{"$setUnion":["$from", "$to"]}}},
{"$project":{"_id":0, users: {"$setDifference":["$userAll", [ObjectId("57f5522099aabf1c0565bbfe")]]}}}
]);
Sample output:
{
"users" : [
ObjectId("57f54e154df8d0193577889b"),
ObjectId("57f54e154df8d0193577889a")
]
}

Related

Filter day on MongoDB

I have a collection called "batches" that has the field "createdAt" with ISODate:
{
"_id" : ObjectId("5f6134ecf908840018f2e9ea"),
"status" : "BATCH_PROCESSING",
"groupId" : 13,
"type" : "not",
"finished" : false,
"scheduledTo" : "2020-09-15T18:50:51-03:00",
"identifier" : "COLABORADORES",
"createdAt" : "2020-09-18T18:41:00-03:00",
"__v" : 0
}
{
"_id" : ObjectId("5f6144d7863bb40018045906"),
"status" : "BATCH_PROCESSING",
"groupId" : 13,
"type" : "not",
"finished" : false,
"scheduledTo" : "2020-09-16T19:48:00-03:00",
"identifier" : "COLABORADORES",
"createdAt" : "2020-09-15T19:48:55-03:00",
"__v" : 0
}
{
"_id" : ObjectId("5f617021b985c1001974c3af"),
"status" : "CANCELED",
"groupId" : 13,
"type" : "not",
"finished" : true,
"scheduledTo" : "2020-09-15T23:06:00-03:00",
"identifier" : "COLABORADORES",
"createdAt" : "2020-09-18T22:53:37-03:00",
"__v" : 0,
"numberOfLines" : 1
}
I need to filter only documents in a specific date. I tried many ways but it didn't bring the documents :
db.getCollection("batches").find(
{ createdAt : {
"$gte": ISODate("2020-09-15T00:00:00Z"),
"$lt": ISODate("2020-09-19T00:00:00Z")
} }
);
db.getCollection("batches").find({ createdAt : Date("2020-09-15")}
);
The query works well, but the answer is always:
Fetched 0 record(s) in 136ms
How do I do this filter correctly?
Your data is malformed. Your field 'createdDate' is a string, not an ISODate(). Consider this...
db.batches.insertMany([
{
"_id" : ObjectId("5f6134ecf908840018f2e9ea"),
"status" : "BATCH_PROCESSING",
"groupId" : 13,
"type" : "not",
"finished" : false,
"scheduledTo" : "2020-09-15T18:50:51-03:00",
"identifier" : "COLABORADORES",
"createdAt" : ISODate("2020-09-18T18:41:00-03:00"),
"__v" : 0
},
{
"_id" : ObjectId("5f6144d7863bb40018045906"),
"status" : "BATCH_PROCESSING",
"groupId" : 13,
"type" : "not",
"finished" : false,
"scheduledTo" : "2020-09-16T19:48:00-03:00",
"identifier" : "COLABORADORES",
"createdAt" : ISODate("2020-09-15T19:48:55-03:00"),
"__v" : 0
},
{
"_id" : ObjectId("5f617021b985c1001974c3af"),
"status" : "CANCELED",
"groupId" : 13,
"type" : "not",
"finished" : true,
"scheduledTo" : "2020-09-15T23:06:00-03:00",
"identifier" : "COLABORADORES",
"createdAt" : ISODate("2020-09-18T22:53:37-03:00"),
"__v" : 0,
"numberOfLines" : 1
}]
)
Query
When applying the query in your post...
db.getCollection("batches").find(
{ createdAt : {
"$gte": ISODate("2020-09-15T00:00:00Z"),
"$lt": ISODate("2020-09-19T00:00:00Z")
} })
... we now see the following results:
MongoDB Enterprise replSet:PRIMARY> db.getCollection("batches").find(
... { createdAt : {
... "$gte": ISODate("2020-09-15T00:00:00Z"),
... "$lt": ISODate("2020-09-19T00:00:00Z")
... } })
{ "_id" : ObjectId("5f6134ecf908840018f2e9ea"), "status" : "BATCH_PROCESSING", "groupId" : 13, "type" : "not", "finished" : false, "scheduledTo" : "2020-09-15T18:50:51-03:00", "identifier" : "COLABORADORES", "createdAt" : ISODate("2020-09-18T21:41:00Z"), "__v" : 0 }
{ "_id" : ObjectId("5f6144d7863bb40018045906"), "status" : "BATCH_PROCESSING", "groupId" : 13, "type" : "not", "finished" : false, "scheduledTo" : "2020-09-16T19:48:00-03:00", "identifier" : "COLABORADORES", "createdAt" : ISODate("2020-09-15T22:48:55Z"), "__v" : 0 }

Mongoose Return One Object from Array

I use mongoose and I have this data in my mongodb :
"_id" : ObjectId("5f13e1edf7c56a896987c191"),
"deleted" : false,
"email" : "klinikkoding#gmail.com",
"firstName" : "Klinik",
"lastName" : "Koding",
"resetToken" : null,
"workspaces" : [
{
"status" : "active",
"_id" : ObjectId("5f13e124f7c56a896987c18e"),
"code" : "kk",
"name" : "Klinik Koding",
"_roleId" : ObjectId("5f13de3eb33fa33ce2a3b0dd")
},
{
"status" : "invited",
"_id" : ObjectId("5f13e13ff7c56a896987c190"),
"code" : "rm",
"name" : "The Manage",
"_roleId" : ObjectId("5f13de3eb33fa33ce2a3b0dd")
}
],
How can I return only one workspace? The output that I need is like this:
"_id" : ObjectId("5f13e1edf7c56a896987c191"),
"deleted" : false,
"email" : "klinikkoding#gmail.com",
"firstName" : "Klinik",
"lastName" : "Koding",
"resetToken" : null,
"workspaces" : [
{
"status" : "active",
"_id" : ObjectId("5f13e124f7c56a896987c18e"),
"code" : "kk",
"name" : "Klinik Koding",
"_roleId" : ObjectId("5f13de3eb33fa33ce2a3b0dd")
},
],
Anyone can help me with this query?
Try this.
async function retrieve(){
// You can retrieve it by any field. I used email because it is unique.
let data=await yourModelName.findOne({email:"klinikkoding#gmail.com"})
data.workspaces.splice(1,1)
console.log("your final result",data)
}
retrieve()

mongodb findOne not found document in base

in my collection i have this document:
{
"_id" : ObjectId("5eecb84a9e41ff609fd6389a"),
"uid" : NumberLong(619942065802969109),
"banmute" : 0,
"expire" : ISODate("2023-03-15T13:06:18.694Z"),
"fid" : "3cac4490b6ca491e838d4e5317e5b87e",
"id" : null,
"nick" : "Flawe",
"nicks_ld" : "",
"old_nicks" : "",
"reason" : ""
}
Indexes is:
/* 1 */
[
{
"v" : 2,
"key" : {
"_id" : 1
},
"name" : "_id_",
"ns" : "fsl.index_profile"
},
{
"v" : 2,
"unique" : true,
"key" : {
"uid" : 1
},
"name" : "uid_1",
"ns" : "fsl.index_profile",
"background" : true
}
]
On direct request i have null answer:
db.getCollection('index_profile').findOne({uid: 619942065802969109})
result: ->
null
But if i request $gte i found it:
db.getCollection('index_profile').find({uid: {$gte: 619942065802969109}}).limit(1)
result: ->
/* 1 */
{
"_id" : ObjectId("5eecb84a9e41ff609fd6389a"),
"uid" : NumberLong(619942065802969109),
"banmute" : 0,
"expire" : ISODate("2023-03-15T13:06:18.694Z"),
"fid" : "3cac4490b6ca491e838d4e5317e5b87e",
"id" : null,
"nick" : "Flawe",
"nicks_ld" : "",
"old_nicks" : "",
"reason" : ""
}
I tried deleting the cache, rebooting the server, deleting indexes, assigned different new indexes
I am in despair, help solve this problem
have you tried:
db.getCollection('index_profile').findOne({uid: NumberLong(619942065802969109)})

Issue with firebase query

My query:
let query = recentRef.queryOrderedByChild(FRECENT_GROUPID).queryEqualToValue(group_id)
query.observeSingleEventOfType(.Value, withBlock: { snapshot in
And database structure is :
And my query looks like:
(/Recent {
ep = fb343534ca520c70fe35b0a316ea8e4c;
i = groupId;
sp = fb343534ca520c70fe35b0a316ea8e4c;
})
and getting Snap (Recent) <null> when I print(snapshot).
Its strange that it was working fine but now its suddenly stopped working.
EDIT:
Complete JSON:
{
"Message" : {
"fb343534ca520c70fe35b0a316ea8e4c" : {
"-Kp0jed1EZ5BLllL5_cm" : {
"createdAt" : 1.500046597341153E9,
"groupId" : "fb343534ca520c70fe35b0a316ea8e4c",
"objectId" : "-Kp0jed1EZ5BLllL5_cl",
"senderId" : "lI6SRppSboScWo5xVjcfLL82Ogr2",
"senderName" : "Test1 Test1",
"status" : "",
"text" : "hi",
"type" : "text",
"updatedAt" : 1.50004659734136E9
}
}
},
"Recent" : {
"-Kp0jecwejhzQbbm62CW" : {
"counter" : 0,
"createdAt" : 1.500046600967624E9,
"description" : "Test1 Test1",
"groupId" : "fb343534ca520c70fe35b0a316ea8e4c",
"lastMessage" : "hi",
"members" : [ "lI6SRppSboScWo5xVjcfLL82Ogr2", "fnRvHFpaoDhXqM1se7NoTSiWZIZ2" ],
"objectId" : "-Kp0jecwejhzQbbm62CV",
"picture" : "",
"type" : "private",
"updatedAt" : 1.500046600967647E9,
"userId" : "fnRvHFpaoDhXqM1se7NoTSiWZIZ2"
},
"-Kp0jed-FU1PXt1iPr29" : {
"counter" : 0,
"createdAt" : 1.500046600971885E9,
"description" : "Srikant Root",
"groupId" : "fb343534ca520c70fe35b0a316ea8e4c",
"lastMessage" : "hi",
"members" : [ "lI6SRppSboScWo5xVjcfLL82Ogr2", "fnRvHFpaoDhXqM1se7NoTSiWZIZ2" ],
"objectId" : "-Kp0jed-FU1PXt1iPr28",
"picture" : "https://s3.amazonaws.com/top500golfdev/uploads/profile/srikant.yadav#rootinfosol.com/profilepicture.jpg",
"type" : "private",
"updatedAt" : 1.500046600971896E9,
"userId" : "lI6SRppSboScWo5xVjcfLL82Ogr2"
}
},
"User" : {
"fnRvHFpaoDhXqM1se7NoTSiWZIZ2" : {
"createdAt" : 1.500045753102713E9,
"email" : "srikant.yadav#rootinfosol.com",
"firstname" : "Srikant",
"fullname" : "Srikant Yadav",
"handle" : "Srikant",
"lastname" : "Yadav",
"networkImage" : "https://s3.amazonaws.com/top500golfdev/uploads/profile/srikant.yadav#rootinfosol.com/profilepicture.jpg",
"objectId" : "fnRvHFpaoDhXqM1se7NoTSiWZIZ2",
"online" : false,
"updatedAt" : 1.500045753102731E9
},
"lI6SRppSboScWo5xVjcfLL82Ogr2" : {
"createdAt" : 1.500045791892967E9,
"email" : "test1#gmail.com",
"firstname" : "Test1",
"fullname" : "Test1 Test1",
"handle" : "test1",
"lastname" : "Test1",
"networkImage" : "",
"objectId" : "lI6SRppSboScWo5xVjcfLL82Ogr2",
"online" : false,
"updatedAt" : 1.500046571456235E9
}
}
}

Inconsistent query results with embedded documents on MongoDB

I've got a collection called payments with an example of its document shown below:
{
"_id" : ObjectId("579b5ee817e3aaac2f0aebc1"),
"updatedAt" : ISODate("2016-07-29T11:04:01.209-03:00"),
"createdAt" : ISODate("2016-07-29T10:49:28.113-03:00"),
"createdBy" : ObjectId("5763f56010cd7b03008147d4"),
"contract" : ObjectId("578cb907f1575f0300d84d09"),
"recurrence" : [
{
"when" : ISODate("2016-05-29T11:03:45.606-03:00"),
"_id" : ObjectId("579b6241ea945e3631f64e2d"),
"transaction" : {
"createdAt" : ISODate("2016-05-29T11:03:45.608-03:00"),
"tid" : "9999999999999999B01A",
"status" : 4,
"code" : "00",
"message" : "Transação autorizada"
},
"status" : "PAGO"
},
{
"when" : ISODate("2016-06-29T11:03:45.608-03:00"),
"_id" : ObjectId("579b6241ea945e3631f64e2c"),
"transaction" : {
"createdAt" : ISODate("2016-06-29T11:03:45.608-03:00"),
"tid" : "9999999999999999B01A",
"status" : 4,
"code" : "00",
"message" : "Transação autorizada"
},
"status" : "PAGO"
},
{
"when" : ISODate("2016-07-29T11:03:45.608-03:00"),
"_id" : ObjectId("579b6241ea945e3631f64e2b"),
"status" : "ERRO",
"transaction" : {
"code" : "56",
"createdAt" : ISODate("2016-07-29T11:04:01.196-03:00"),
"message" : "Autorização negada",
"status" : 5,
"tid" : "1006993069000730B88A"
}
},
{
"when" : ISODate("2016-07-30T11:03:45.608-03:00"),
"_id" : ObjectId("579b6241ea945e3631f64e2a"),
"status" : "PENDENTE"
},
{
"when" : ISODate("2016-07-31T11:03:45.608-03:00"),
"_id" : ObjectId("579b6241ea945e3631f64e29"),
"status" : "PENDENTE"
},
{
"when" : ISODate("2016-08-01T11:03:45.608-03:00"),
"_id" : ObjectId("579b6241ea945e3631f64e28"),
"status" : "PENDENTE"
}
],
"status" : "PAGO",
"conditions" : {
"originalValue" : 7406.64,
"totalValue" : 7400,
"upfrontValue" : 1500,
"upfrontInstallments" : 3,
"balanceInstallments" : 9
},
"__v" : 0,
"transaction" : {
"code" : "00",
"createdAt" : ISODate("2016-07-29T10:49:46.610-03:00"),
"message" : "Transação autorizada",
"status" : 6,
"tid" : "1006993069000730AF5A"
}
}
If I run the query below, I get the desired document shown above:
db.payments.find({ "recurrence.transaction.tid": "1006993069000730B88A" })
However, if I run this other query, MongoDB returns my entire collection (presumably because it didn't match the subdocument's id):
db.payments.find({ "recurrence._id": ObjectId("579b6241ea945e3631f64e2b") })
Both queries should return the same result! I also checked some other questions including this one so unless I'm going crazy I'm doing the same thing. Not sure why the inconsistent results though.
Tryout this:
db.payments.find({ recurrence : { $elemMatch: { "transaction.tid": "1006993069000730B88A"} } }).pretty()