Query MongoDB with DBRef - mongodb

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

Related

Delete a child record from a specific parent record

I am pretty new to mongodb. I have 3 levels of documents.
Parent > Child > Child, all having _id field.
{
"_id" : "n2qw5sojs4bajrj",
"Title" : "Mr",
"Instance" : "HQ",
"FirstName" : "ppp",
"LastName" : "uuuu",
"Position" : "BF",
"EmailAddress" : "xxx#ppp.com",
"Requests" : [
{
"_id" : "121",
"Date" : "12/02/2018",
"Status" : "New",
"ApprovedBy" : {
"_id" : "sdfsdf",
"Name" : "MAN"
},
"PPE" : [
{
"_id" : "121",
"Code" : "PPE",
"Status" : "New",
"Title" : "Trousers",
"Type" : "STD",
"Size" : "10111116",
"Qty" : 1,
"LostDamage" : {
"Reason" : "asdaD",
"Location" : "Station",
"Damage" : "Damged"
}
},
{
"_id" : "122",
"Code" : "PPEOPP",
"Status" : "New",
"Title" : "TrousASDASDASDers",
"Type" : "STD",
"Size" : "10111116",
"Qty" : 1,
"LostDamage" : {
"Reason" : "asdaD",
"Location" : "Station",
"Damage" : "Damged"
}
}
]
}
]
}
I would like find out how to delete the last PPE Element (Parent > Request > PPE) by the _id column.
So I would to delete the following child:
{
"_id" : "121",
"Code" : "PPE",
"Status" : "New",
"Title" : "Trousers",
"Type" : "STD",
"Size" : "10111116",
"Qty" : 1,
"LostDamage" : {
"Reason" : "asdaD",
"Location" : "Station",
"Damage" : "Damged"
}
}
Any tips / help would be great.
Thanks
Paul
You can use MongoDb $pop to remove your last element from array. Like this go to https://docs.mongodb.com/manual/reference/operator/update/pop/
db.collection.update({id:1}, { $pop:{ 'request.PPE':1}});

I cannot query with two collections joining with $lookup

can anyone help me? I have two collections. And I want to query joining these two collections. I used aggerate method and $lookup but I still get error.
First collection (bill_history)
{
"_id" : ObjectId("59856d04f81b08b4f61a6bea"),
"id" : 262.0,
"category" : "Beauty",
"holdername" : "Blue Planet",
"serviceid" : 156.0,
"keyword" : "BEA",
"source" : "8602",
"amount" : 84.0,
"billfrequency" : "daily",
"smsfrequency" : "1sms per day",
"type" : "Subscription",
"description" : "Beauty Tips",
"status" : "running",
"startdate" : "2016-09-10 11:28:47",
"enddate" : "1970-01-01 00:00:01",
"contact" : "12399188",
"remark" : "Content SMS Service (CMS)"
}
Second Collection (service)
{
"_id" : ObjectId("59856d04f81b08b4f61a6bea"),
"id" : 262.0,
"category" : "Beauty",
"holdername" : "Blue Planet",
"serviceid" : 156.0,
"keyword" : "BEA",
"source" : "8602",
"amount" : 84.0,
"billfrequency" : "daily",
"smsfrequency" : "1sms per day",
"type" : "Subscription",
"description" : "Beauty Tips",
"status" : "running",
"startdate" : "2016-09-10 11:28:47",
"enddate" : "1970-01-01 00:00:01",
"contact" : "12399188",
"remark" : "Content SMS Service (CMS)"
}
My Mongo Query Code is as below.
db.bill_history.aggregate([
{ $lookup : {
from : "service",
localField : "ref",
foreignField : "keyword",
as : "embaddedData"
}
}
])
Error message and code are as below.
"error msg":"exception: Unrecognized pipeline stage name: '$lookup'",
"code" : 16436,

Why Iam getting this value as a NULL

I am getting the below erro, when I provide the findOne function. It is displaying NULL, couldn't find the solution as there are records with the title.
db.links.findOne({title: "MongoDB TUtor"});
{
"_id" : ObjectId("54f3ea83663952fddd7aaa54"),
"title" : "MongoDB TUtor",
"url" : "mongo.com",
"comment" : "document-oriented db"
}
> db.links.findOne({title: "true"});
null
> db.links.findOne({title: 1});
null
--
Records in links collection
db.links.find().forEach(printjson)
{
"_id" : ObjectId("54f3ea83663952fddd7aaa54"),
"title" : "MongoDB TUtor",
"url" : "mongo.com",
"comment" : "document-oriented db"
}
{
"_id" : ObjectId("54f3ebe7663952fddd7aaa55"),
"title" : "Mongo DB handson",
"url" : "https://university.mongo.com",
"comment" : [
"NoSQL",
"Document-based"
],
"filed_on" : ISODate("2015-03-02T04:47:02.131Z"),
"meta" : {
"browser" : [
"Google Chrome",
"MAC Safari"
],
"version" : "13.4.3.7"
}
}
{
"_id" : ObjectId("54f3f77e663952fddd7aaa5a"),
"title" : "MongoDB_database",
"url" : "mongo.com",
"comment" : "document-oriented db"
}
{
"_id" : ObjectId("54f3f7b7663952fddd7aaa5c"),
"title" : "database",
"url" : "mongo.com",
"comment" : "document-oriented db"
}
{ "_id" : ObjectId("54f3fa5f663952fddd7aaa5d"), "title" : "Rocky" }
{
"_id" : ObjectId("54f3facf663952fddd7aaa5e"),
"title" : "Arnold",
"userId" : ObjectId("54f3fa5f663952fddd7aaa5d")
}
> db.links.find().pretty()
{
"_id" : ObjectId("54f3ea83663952fddd7aaa54"),
"title" : "MongoDB TUtor",
"url" : "mongo.com",
"comment" : "document-oriented db"
}
{
"_id" : ObjectId("54f3ebe7663952fddd7aaa55"),
"title" : "Mongo DB handson",
"url" : "https://university.mongo.com",
"comment" : [
"NoSQL",
"Document-based"
],
"filed_on" : ISODate("2015-03-02T04:47:02.131Z"),
"meta" : {
"browser" : [
"Google Chrome",
"MAC Safari"
],
"version" : "13.4.3.7"
}
}
{
"_id" : ObjectId("54f3f77e663952fddd7aaa5a"),
"title" : "MongoDB_database",
"url" : "mongo.com",
"comment" : "document-oriented db"
}
{
"_id" : ObjectId("54f3f7b7663952fddd7aaa5c"),
"title" : "database",
"url" : "mongo.com",
"comment" : "document-oriented db"
}
{ "_id" : ObjectId("54f3fa5f663952fddd7aaa5d"), "title" : "Rocky" }
{
"_id" : ObjectId("54f3facf663952fddd7aaa5e"),
"title" : "Arnold",
"userId" : ObjectId("54f3fa5f663952fddd7aaa5d")
}
That's not how you do it. The way you are querying this it is looking for an actual document that either has "title": true or "title": 1. Of course, none of your documents meet that condition.
When you want to find out if that field is "actually there" then you use the $exists operator to test for the presence:
db.links.findOne({ "title": { "$exists": true } })
Or naturally with the reverse case when looking for documents that do not have the matching field.

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

MongoTemplate find not returning results

MongoTemplate not returning results.
Json:
{
"_id" : ObjectId("51acf6ab0d5d46077ae12b2a"),
"docType" : "row",
"value" : {
"entity" : {
"#id" : "1111",
"#version" : "3434",
"name" : "XY XY",
"listId" : 28,
"listCode" : "BS",
"entityType" : "03",
"createdDate" : "09/12/2006",
"lastUpdateDate" : "04/20/2011",
"source" : "CCC",
"address1" : "XXXXXXXX",
"city" : "CITY",
"country" : "CO",
"countryName" : "COUNTRY NAME"
}
},
"createdDate" : ISODate("2013-06-03T20:03:55.127Z"),
"createdBy" : "Test"
}
Query:
queryy = new Query(Criteria.where("docType").is("row").andOperator(Criteria.where("value.entity.city").is("CITY")));
Above query doesn't return any result back.
Am I missing something? Please help.
Try this:
query = new Query(Criteria.where("docType").is("row")
.and("value.entity.city").is("CITY"));
You're code doesn't need the andOperator function (as that translates to $and). It just needs multiple criteria using and.
And, you can use query.toString() to see what the output would be of the query (and compare it to what you might have used in the MongoDB shell.