index search returns all subdocuments - mongodb

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 }}}
})

Related

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 MongoDB with DBRef

I have a table in mongo db called documents
{
"_id" : ObjectId("565a7f1"),
"_class" : "Document", "name" :
"Book Template",
"location" : "/Book Template.pdf",
"type" : DBRef("types", ObjectId("3eaabf5"))
},
{
"_id" : ObjectId("565a7f2),
"_class" : "Document",
"name" : "Sample Contract",
"location" : "/Sample Contract.pdf",
"type" : DBRef("types", ObjectId("3eaabf5"))
},
{
"_id" : ObjectId("565a7f3"),
"_class" : "Document",
"name" : "Clustering with RabbitMQ",
"location" : "/Clustering with RabbitMQ.txt",
"type" : DBRef("types", ObjectId("3eaabf6"))
}
and then I have a table called types
{
"_id" : ObjectId("3eaabf5"),
"_class" : "Type",
"name" : "PDF",
"description" : "Portable Document Format",
"extension" : ".pdf"
};
{
"_id" : ObjectId("3eaabf6"),
"_class" : "Type",
"name" : "NOTE",
"description" : "Text Notes",
"extension" : ".txt"
},
{
"_id" : ObjectId("3eaabf7"),
"_class" : "Type",
"name" : "WEB",
"description" : "Web Link",
"extension" : ".url"
}
I want to query the documents table for all documents which have an extension of PDF.
So I wrote the following queries... but everything returns empty results.
>db.documents.find({"types.$id":"3eaabf5"})
>
>db.documents.find({"types.name":"PDF"})
>
You may try this
db.documents.find({"type.$id":ObjectId("3eaabf5")}

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" }}
]
)

Updating complete embedded document in MongoDB

I am new to mongoDB, and I am stuck at a simple update operation:
Here is the document that I had stored:
{
"_id" : "xyz",
"basicinfo_showcase_components" : {
"display_name" : "ritesh",
"display_email" : "xyz#gmail.comxsa",
"international_phone_number" : "+91 .....",
},
"address_components" : {
"country" : "India",
"postal_code" : "500004",
"state" : "Telangana",
"city" : "Hyderabad",
"subLocality1" : "aaaa",
"subLocality2" : "",
"subLocality3" : "",
"route" : "",
"geometry" : {
"lat" : 17.43143576387407,
"lng" : 78.464432457672046
},
"formatted_address" : "addrr"
}
}
Now I want to updat the address_components in above document:
I tried:
db.portfolio.update({ "_id" : "xyz", "$isolated" : "true" },
{
"address_components" : {
"country" : "Nepal",
"postal_code" : "878799",
"state" : "Telangana",
"city" : "Kathmandu",
"subLocality1" : "xyz",
"subLocality2" : "",
"subLocality3" : "",
"route" : "",
"geometry" : {
"lat" : 17.43143576387407,
"lng" : 78.464432457672046
},
"formatted_address" : "kath..."
}
});
But after updating, the "basicinfo_showcase_components" is eliminated.
ie. the updated doc is:
{
"_id" : "ohris",
"address_components" : {
.......
}
}
Can you please point out the mistake?
In your update query you passed whole document as your update document, if you want to update just one (or more) fields of document you should use $set operator:
db.test.update({ "_id" : "xyz", "$isolated" : "true" },
{
$set : {
"address_components" : {
"country" : "Nepal",
"postal_code" : "878799",
"state" : "Telangana",
"city" : "Kathmandu",
"subLocality1" : "xyz",
"subLocality2" : "",
"subLocality3" : "",
"route" : "",
"geometry" : {
"lat" : 17.43143576387407,
"lng" : 78.464432457672046
},
"formatted_address" : "kath..."
}
}});

need to find a way to get data inside subdocument in mongo

I need a way to find inside nested array documents.
I want to find value matching inside street_1.
this is my query:
db.phonebook.find({'address.home.street_1' : 'street 1 result'});
and my document:
{
"_id" : ObjectId("53788c0c74d3ead0098b4568"),
"first_name" : "jarod",
"last_name" : "petters",
"company" : "nostromos",
"phone_numbers" : [
{
"cell" : "0752203337"
},
{
"home" : "0850819201"
},
{
"home" : "0499955550"
}
],
"website" : "http://www.mywebsite.com",
"email" : [
{
"home" : "email.first.com"
},
{
"office" : "email.second.com"
}
],
"address" : [
{
"home" : {
"stree_1" : "street 1 result",
"stree_2" : "",
"postal_code" : "66502",
"city" : "my littre city",
"country" : "usa"
}
}
],
"nationality" : "mars",
"date_of_birth" : "1978-01-01"
}
Your query is the good one. But your document is not good, you have done a mistake in your document, you write stree_1 instead of street_1. If your document is right, change your query to :
db.phonebook.find({'address.home.stree_1' : 'street 1 result'});