Need to count field based on value in mongodb - mongodb

We have mongo 3.2. we have collection name test5.
It has many field and array ( undaries.couies.ZIPCodes.status )
Status field has few values like Add1 & Add2
I want to take COUNT based on status=ADD1 or ADD2
"**undaries**" : [
{
"**couies**" : [
{
"**ZIPCodes**" : [
{
"ZIPCode" : "60349",
"city" : "Test",
"household" : "Test2",
"accounts" : "0",
"SD" : "Y",
"**status**" : "Add1",
"lastUpdateDate" : "2017-01-24T09:39:56.417Z",
"lastUpdateBy" : "Test"
},
{
"ZIPCode" : "60234",
"city" : "Test",
"household" : "test1",
"accounts" : "0",
"SD" : "Y",
"status" : "Add2",
"lastUpdateDate" : "2017-01-24T09:39:56.417Z",
"lastUpdateBy" : "Test"
},
{
"ZIPCode" : "60235",
"city" : "Test",
"household" : "test1",
"accounts" : "0",
"SD" : "Y",
"status" : "Add1",
"lastUpdateDate" : "2017-01-24T09:39:56.417Z",
"lastUpdateBy" : "Test"
}................
How to get total count of status based on value.
Thanks & Regards.

You may use the count() method and the $in operator
db.yourCollection.count({"undaries.couies.ZIPCodes.status":{$in : ["Add1", "Add2"]}})
count() is shorthand for .find({query}).count()

Related

Find distinct field in multiple same collections mongodb

I have 7 collections in one database that the collections are the same and I have to find a unique field in those collections and count it or show it in a new collection named result.
I tried lookup but it it did not work. Can anyone guide me how to do the job?
These are 7 collections: 20200309-20200310-20200311-20200312-20200313-20200314-20200315 and result is the collection for store the result of query.
col : 20200309
{
"_id" : ObjectId("5e6f7c7c0371c86b8737628b"),
"sid" : 13328,
"trans-id" : "PROV_158374123364907198165",
"status" : "1",
"base-price-point" : "6000",
"msisdn" : "989115506327",
"keyword" : "",
"validity" : 0,
"next_renewal_date" : "",
"shortcode" : "",
"billed-price-point" : "",
"trans-status" : 0,
"chargeCode" : "AVMREWCAVMAW6000",
"datetime" : "2020-03-09 11:37:13.649",
"event-type" : "1.5",
"channel" : "system"
}
{
"_id" : ObjectId("5e6f7c7c0371c86b8737628c"),
"sid" : 13328,
"trans-id" : "PROV_158374123384007267165",
"status" : "1",
"base-price-point" : "6000",
"msisdn" : "989107351827",
"keyword" : "",
"validity" : 0,
"next_renewal_date" : "",
"shortcode" : "",
"billed-price-point" : "",
"trans-status" : 0,
"chargeCode" : "AVMREWCAVMAW6000",
"datetime" : "2020-03-09 11:37:13.840",
"event-type" : "1.5",
"channel" : "system"
}
col : 20200310
{
"_id" : ObjectId("5e6f7d140371c86b873e6bce"),
"sid" : 13328,
"trans-id" : "PROV_158383144246275616515",
"status" : "1",
"base-price-point" : "6000",
"msisdn" : "989909789746",
"keyword" : "",
"validity" : 0,
"next_renewal_date" : "",
"shortcode" : "",
"billed-price-point" : "",
"trans-status" : 0,
"chargeCode" : "AVMREWCAVMAW6000",
"datetime" : "2020-03-10 12:40:42.462",
"event-type" : "1.5",
"channel" : "system"
}
{
"_id" : ObjectId("5e6f7d140371c86b873e6bcf"),
"sid" : 13328,
"trans-id" : "PROV_158382430015338271227",
"status" : "1",
"base-price-point" : "6000",
"msisdn" : "989901812412",
"keyword" : "",
"validity" : 0,
"next_renewal_date" : "",
"shortcode" : "",
"billed-price-point" : "",
"trans-status" : 0,
"chargeCode" : "AVMREWCAVMAW6000",
"datetime" : "2020-03-10 10:41:40.153",
"event-type" : "1.5",
"channel" : "system"
}
and there is 5 collections like above
The following script can be used to get distinct msisdn values in an array and the count. Run the script from the mongo shell.
For this to run efficiently, there needs to be an index on the two fields msisdn and status as: { status: 1, msisdn: 1}. The index needs to be created on all the collections. Note the indexes are not required in case the collections have just few thousand documents.
collections = [ "20200309", "20200310", // ... ]
combined = [ ]
for (let coll of collections) {
combined = combined.concat( db.getCollection(coll).distinct( "msisdn", { status: "1" } ) )
}
combined = [...new Set(combined) ]
print('Combined count:', combined.length)
The combined = [...new Set(combined) ] statement removes duplicates from the combined distinct values from the seven collections.

Nested object update query in mongodb

I have object in my procedures collection.
I want to update item_status of item_id 5996c80fca423ce1228f7690 which is available in preferences.items.
I want to get all records who has mentioned item_id so that we can update all occurrences.
{
"_id" : ObjectId("5996d0a1ca423ce1228f777a"),
"status" : "Active",
"procedure_name" : "ATHA",
"procedure_for" : "Admin",
"created_by" : "5940c3e8734d1d79866338cf",
"created_on" : ISODate("2017-10-19T18:44:22.702+0000"),
"speciality_id" : "5751131e3a1253845560a984",
"speciality" : "Orthopdics",
"master_template_id" : "",
"hospital_id" : "",
"surgeon_nurse_id" : "",
"procedure_type" : "Published",
"published_on" : ISODate("2017-10-19T18:44:22.702+0000"),
"surgical_sequence" : [
],
"preferences" : [
{
"category_id" : "5971fae84658f5241d8a5b70",
"category" : "Instruments",
"_id" : ObjectId("59e8f2861c999f292a837304"),
"items" : [
{
"item_id" : "5996c80fca423ce1228f7690",
"item_name" : "Battery",
"item_description" : "",
"image_name" : "BATTERY.png",
"icon_image" : "",
"side_view_image" : "",
"_id" : ObjectId("59e8f2861c999f292a837306"),
"attributes" : [
],
"subcategory" : [
{
"name" : "Power tool",
"subcategory_id" : "5996c80eca423ce1228f7549",
"parent_id" : "",
"_id" : ObjectId("5996c80fca423ce1228f7709")
},
{
"name" : "Battery",
"subcategory_id" : "5996c80eca423ce1228f750e",
"parent_id" : "5996c80eca423ce1228f7549",
"_id" : ObjectId("5996c80fca423ce1228f7708")
}
]
}
]
}
],
"__v" : NumberInt(0),
"modified_by" : "5940c3e8734d1d79866338cf",
"modified_on" : ISODate("2017-10-19T18:44:22.702+0000")
}
I'm assuming you are talking about updating status field since I don't find any field with the name item_status. If that's the case, the below query should work:
> db.procedures.updateMany({"preferences.$.items.$.item_id": "5996c80fca423ce1228f7690"}, {"$set": {"status": "new_status"}})

Query to filter the information from a mongodb collection

I have to retrieve a list of users from list of documents which matches the condition. The document structure look like below
{
"_id" : ObjectId("660ff865d4f9075d40a1101c"),
"orderFormId" : "OF-rJw4elBYK",
"orderDetails" : [
{
"courseId" : "53fc31f443fa1fe885d3ad61",
"userInfo" : [
{
"dob" : "2015-03-22T18:30:00.000Z",
"lastName" : "M",
"status" : "Pending Appproval",
"eMail" : "jihin345#baabte.com",
"firstName" : "Arun"
},
{
"status" : "requested",
"firstName" : "asdasd",
"dob" : "2015-03-23T18:30:00.000Z",
"lastName" : "asdafasd",
"userId" : "RQ-11xDPALgR",
"eMail" : "adsasd#baabte.com"
},
{
"status" : "requested",
"firstName" : "asdaf",
"dob" : "2015-03-23T18:30:00.000Z",
"lastName" : "fsdsdf",
"userId" : "RQ-OdoXAOLrB",
"eMail" : "ashdjasufh#baabte.com"
},
{
"status" : "requested",
"firstName" : "asdas",
"dob" : "2015-03-23T18:30:00.000Z",
"lastName" : "asdasd",
"userId" : "RQ-Bw2Xokmda",
"eMail" : "asdasd#gmail.com"
}
],
"userCount" : 5,
"Name" : "Compilers",
"coursePrice" : 1000,
"coursetype" : "offline"
},
{
"courseId" : "53fc31f443fa1fe885d3ad62",
"userInfo" : [
{
"dob" : "2015-03-22T18:30:00.000Z",
"lastName" : "Raj",
"status" : "requested",
"eMail" : "jihin432#baabte.com",
"firstName" : "Nithul"
},
{
"dob" : "2015-03-22T18:30:00.000Z",
"lastName" : "P C",
"status" : "requested",
"eMail" : "jihin345#baabte.com",
"firstName" : "Kahyoom"
}
],
"userCount" : 1,
"Name" : "Computer Science 101",
"coursePrice" : 0,
"coursetype" : "offline"
},
{
"courseId" : "57fc31f443fa1fe885d3ad64",
"userInfo" : [
{
"status" : "requested",
"firstName" : "asdasd",
"dob" : "2015-03-23T18:30:00.000Z",
"lastName" : "aasdasd",
"userId" : "RQ-WqEXBkjv5",
"eMail" : "asdasd#gmail.com"
}
],
"userCount" : 1,
"coursePrice" : 0,
"Name" : "Introduction to Haptics: Self-Paced",
"coursetype" : "offline"
}
],
"companyId" : ObjectId("54128cc57525614f6e3e710a"),
"createdDate" : ISODate("2015-03-23T11:26:29.027Z"),
"updatedDate" : ISODate("2015-03-24T15:00:33.248Z"),
"crmId" : ObjectId("660ab20bd4f9075d40a10d52"),
"urmId" : ObjectId("660ab20bd4f9075d40a10d52"),
"activeFlag" : 0,
"customCompanyCode" : "baa-106",
"status" : "Pending approval"}
From above document i have to get the users who have the status "Approved" in userInfo object which exists inside this document. I have created one query but this will output all the users who have different status.My query look like below,
db.clnTrainingRequest.find({companyId:ObjectId('54128cc57525614f6e3e710a'), "orderDetails.userInfo.status":{$in:['Approved']}}).toArray()
Please any one help me to sort out this issue
You can use aggregation. You need to $unwind orderDetails and the userInfo arrays and then use the $match to get users with status Approved
db.clnTrainingRequest.aggregate(
[ { "$match": { "companyId": ObjectId('54128cc57525614f6e3e710a') },
{ "$unwind": "$orderDetails" },
{ "$unwind": "$orderDetails.userInfo" },
{ "$match": { "orderDetails.userInfo.status": "Approved" }}
]
)

index search returns all subdocuments

I would like to only return my embedded documents titled 'Listings', based on the text search query. Where may I be going wrong? Creation of the index?
Here is my index:
db.Collection.ensureIndex({"Listings.Title": "text", "Listings.Description" : "text"}, {name: "Search"})
This returns the whole object, only want listings
db.AspNetUsers.runCommand("text", { search: "lawn" })
this returns just listings, but all the listings are included. Not the listings based on the search criteria e.g. 'lawn'
db.AspNetUsers.runCommand("text", { search: "lawn", project: {Listings:1}})
here is my object
{
"_id" : ,
"UserName" : "",
"PasswordHash" : "",
"SecurityStamp" : "",
"Roles" : [],
"Claims" : [],
"Logins" : [],
"ProfileData" : {
"BirthDate" : new Date("3/8/1974 00:00:00"),
"FirstName" : "",
"LastName" : "",
"MiddleName" : "",
"Address" : "",
"Address1" : ,
"City" : "",
"State" : "",
"PostalCode" : "",
"CellPhone" : "",
"HomePhone" : "",
"Location" : {
"type" : "Point",
"coordinates" : [, ]
}
},
"Email" : "",
"ConfirmationToken" : "Confirmed",
"IsConfirmed" : true,
"Listings" : [{
"_id" : ObjectId("5331ac28a5eabf2854085df5"),
"UserId" : ObjectId("5329b43fa5eabf0548490c27"),
"Title" : "Lawn Chairs",
"Description" : "lawn chairs",
"Pictures" : ["5331ac28a5eabf2854085df6", "5331ac28a5eabf2854085df7", "5331ac28a5eabf2854085df8"],
"Category" : {
"_id" : ObjectId("53273ce37dd6c71e1859ab77"),
"Title" : "Leisure"
}
}, {
"_id" : ObjectId("5331ac50a5eabf2854085df9"),
"UserId" : ObjectId("5329b43fa5eabf0548490c27"),
"Title" : "Lawn Ornaments",
"Description" : "lawn ornaments troll frog gnome",
"Pictures" : ["5331ac50a5eabf2854085dfa", "5331ac50a5eabf2854085dfb", "5331ac51a5eabf2854085dfc"],
"Category" : {
"_id" : ObjectId("53273cd57dd6c71e1859ab76"),
"Title" : "Home"
}
}, {
"_id" : ObjectId("5331ac71a5eabf2854085dfd"),
"UserId" : ObjectId("5329b43fa5eabf0548490c27"),
"Title" : "Cell Phone",
"Description" : "Samsung Galaxy S4",
"Pictures" : ["5331ac71a5eabf2854085dfe", "5331ac71a5eabf2854085dff", "5331ac72a5eabf2854085e00"],
"Category" : {
"_id" : ObjectId("53273cd57dd6c71e1859ab76"),
"Title" : "Home"
}
}]
}
You can get just the fields you want using a project parameter. For getting just the Listings element, you could try:
db.AspNetUsers.runCommand("text", {search:"lawn", project:{_id:0, Listings:1}})
EDIT:
The text command will return all documents that contain the search term. You'll get the entire document. If you further want to filter an array inside of the document, you can use the $elemMatch projection operator, in combination with $regex. For example:
db.AspNetUsers.runCommand("text", {
search: "lawn",
project: {_id:0, Listings:{$elemMatch:{ "Title": /lawn/i }}}
})

Using aggregation in MongoDB to select two or more fields of a document

I'm starting to work with MongoDB and I've a question about aggregation. I've a document that use a lot of different fields in different orders. For example:
db.my_collection.insert({ "answers" : [ { "id" : "0", "type" : "text", "value" : "A"}, { "id" : "1", "type" : "text", "value" : "B"}]})
db.my_collection.insert({ "answers" : [ { "id" : "0", "type" : "text", "value" : "C"}, { "id" : "1", "type" : "text", "value" : "A"}]})
I would to execute a query using "answers.id" with "answers.value" to obtain a result.
I tried but didn't get results, in my case, I executed the command:
db.my_collection.aggregate({$match: {"answers.id":"0", "answers.value": "A"}})
And the result was the two responses when I expected only:
{ "answers" : [ { "id" : "0", "type" : "text", "value" : "A"}, { "id" : "1", "type" : "text", "value" : "B"}]
Thank you!!!
You need to use the $elemMatch operator to match a single element of the answers array with both the specified 'id' and 'value'.
Something like this should work:
db.my_collection.aggregate( {
"$match" : {
"answers" {
"$elemMatch" : {
"id" : "0",
"value" : "A"
}
}
}
} )