How can I use mongodb projections with Go and mgo? - mongodb

I am currently trying to extract a single object within a document array inside of mongodb.
This is a sample dataset:
"_id" : ObjectId("564aae61e0c4e5dddb07343b"),
"name" : "The Races",
"description" : "Horse races",
"capacity" : 0,
"open" : true,
"type" : 0,
"races" : [
{
"_id" : ObjectId("564ab9097628ba2c6ec54423"),
"race" : {
"distance" : 3000,
"user" : {
"_id" : ObjectId("5648bdbe7628ba189e011b18"),
"status" : 1,
"lastName" : "Miranda",
"firstName" : "Aramys"
}
}
},
{
"_id" : ObjectId("564ab9847628ba2c81f2f34a"),
"bet" : {
"distance" : 3000,
"user" : {
"_id" : ObjectId("5648bdbe7628ba189e011b18"),
"status" : 1,
"lastName" : "Miranda",
"firstName" : "Aramys"
}
}
},{...}
]
I can successfully query using the following in mongo:
db.tracks.find({"_id": ObjectId("564aae61e0c4e5dddb07343b")}, {"races": { $elemMatch: {"_id": ObjectId("564ab9847628ba2c81f2f34a")}}}).pretty()
I am unable to do the same using mgo and have tried the following:
Using nesting (Throws: missing type in composite literal, missing key in map literal)
// Using nesting (Throws: missing type in composite literal, missing key in map literal)
c.Find(bson.M{{"_id": bson.ObjectIdHex(p.ByName("id"))}, bson.M{"races": bson.M{"$elemMatch": bson.M{"_id": bson.ObjectIdHex(p.ByName("raceId"))}}}}).One(&result)
// Using select (Returns empty)
c.Find(bson.M{"_id": bson.ObjectIdHex(p.ByName("id"))}).Select(bson.M{"races._id": bson.ObjectIdHex(p.ByName("raceId"))}).One(&result)
//As an array (Returns empty)
c.Find([]bson.M{{"_id": bson.ObjectIdHex(p.ByName("id"))}, bson.M{"races": bson.M{"$elemMatch": bson.M{"_id": bson.ObjectIdHex(p.ByName("raceId"))}}}}).One(&result)
I am using httprouter and p.ByName("...") invocations are parameters passed to the handler.
Thanks in advance.

Would go with the Select method as the doc states that this enables selecting which fields should be retrieved for the results found, thus the projection using $elemMatch operator can be applied here in conjuction with Select, with your final query looking something like:
c.Find(bson.M{
"_id": bson.ObjectIdHex(p.ByName("id"))
}).Select(bson.M{
"races": bson.M{
"$elemMatch": bson.M{
"_id": bson.ObjectIdHex(p.ByName("raceId"))
}
}
}).One(&result)

Related

How to PULL multiple value from a list in a document in mongoDB? [duplicate]

Hi I'm trying to remove multiple objects from an array that looks like this.
{
"_id" : ObjectId("5a7da1bda21d5f3e8cf005b3"),
"owner" : "1",
"group_name" : "PAASCU Board",
"group_members" : [
{
"faculty_name" : "Cheska Dela Rosa",
"faculty_number" : 2,
"_id" : ObjectId("5a7da1bda21d5f3e8cf005b5")
},
{
"faculty_name" : "Earl Sempio",
"faculty_number" : 7323,
"_id" : ObjectId("5a7da1bda21d5f3e8cf005b4")
},
{
"faculty_number" : 203,
"faculty_name" : "Sample",
"_id" : ObjectId("5a7dbf7952bd150a94d83958")
},
{
"faculty_number" : 8025,
"faculty_name" : "Sample Postman",
"_id" : ObjectId("5a7dc64a1cf5dd3d50167d53")
}
],
"__v" : 0 }
It works when I remove a single object using the $pull with this code.
db.getCollection('groups').update({_id: ObjectId("5a7da1bda21d5f3e8cf005b3")}, {$pull: {"group_members": {"faculty_number":8025}}})
But what if I want to remove multiple objects with different faculty_number? I tried using the $each method just like how I add multiple objects in the array but it doesn't work well.
Use $in operator to pass the list of faculty values to remove documents from embedded array. More here
Try
db.groups.update(
{"_id": ObjectId("5a7da1bda21d5f3e8cf005b3")},
{"$pull":{"group_members":{"faculty_number":{$in:[8025,7323]}}}}
)

Mongodb aggregate lookup return only one field of array

i have some collections for our project.
Casts collection contains movie casts
Contents collection contains movie contents
i want to run aggregate lookup for get information about movie casts with position type.
i removed collections details unnecessary fields.
Casts details:
{
"_id" : ObjectId("5a6cf47415621604942386cd"),
"fa_name" : "",
"en_name" : "Ehsan",
"fa_bio" : "",
"en_bio" : ""
}
Contents details:
{
"_id" : ObjectId("5a6b8b734f1408137f79e2cc"),
"casts" : [
{
"_id" : ObjectId("5a6cf47415621604942386cd"),
"fa_fictionName" : "",
"en_fictionName" : "Ehsan2",
"positionType" : {
"id" : 3,
"fa_name" : "",
"en_name" : "Director"
}
},
{
"_id" : ObjectId("5a6cf47415621604942386cd"),
"fa_fictionName" : "",
"en_fictionName" : "Ehsan1",
"positionType" : {
"id" : 3,
"fa_name" : "",
"en_name" : "Writers"
}
}
],
"status" : 0,
"created" : Timestamp(1516997542, 4),
"updated" : Timestamp(1516997542, 5)
}
when i run aggregate lookup with bellow query, in new generated lookup array only one casts contents If in accordance with above casts array value aggregate lookup should return two casts content with two type. in casts array value exists two type of casts, 1) writers and directors. but returned director casts content. _casts should contains two object not one object!
aggregate lookup query:
{$lookup:{from:"casts",localField:"casts._id",foreignField:"_id",as:"_casts"}}
result:
{
"_id" : ObjectId("5a6b8b734f1408137f79e2cc"),
"casts" : [
{
"_id" : ObjectId("5a6cf47415621604942386cd"),
"fa_fictionName" : "",
"en_fictionName" : "Ehsan2",
"positionType" : {
"id" : 3,
"fa_name" : "",
"en_name" : "Director"
}
},
{
"_id" : ObjectId("5a6cf47415621604942386cd"),
"fa_fictionName" : "",
"en_fictionName" : "Ehsan1",
"positionType" : {
"id" : 3,
"fa_name" : "",
"en_name" : "Writers"
}
}
],
"_casts" : [
{
"_id" : ObjectId("5a6cf47415621604942386cd"),
"fa_name" : "",
"en_name" : "Ehsan",
"fa_bio" : "",
"en_bio" : ""
}
],
"status" : 0,
"created" : Timestamp(1516997542, 4),
"updated" : Timestamp(1516997542, 5)
}
EDIT-1
finally my problem is solved. i have only one problem with this query, this query doesn't show root document fields. finally solve this problem. finally query exists in EDIT-2.
query:
db.contents.aggregate([
{"$unwind":"$casts"},
{"$lookup":{"from":"casts","localField":"casts._id","foreignField":"_id","as":"casts.info"}},
{"$unwind":"$casts.info"},
{"$group":{"_id":"$_id", "casts":{"$push":"$casts"}}},
])
EDIT-2
db.contents.aggregate([
{"$unwind":"$casts"},
{"$lookup":{"from":"casts","localField":"casts._id","foreignField":"_id","as":"casts.info"}},
{"$unwind":"$casts.info"},
{$group:{"_id":"$_id", "data":{"$first":"$$ROOT"}, "casts":{"$push":"$casts"}}},
{$replaceRoot:{"newRoot":{"$mergeObjects":["$data",{"casts‌​":"$casts"}]}}},
{$project:{"casts":0}}
]).pretty()
This is expected behavior.
From the docs,
If your localField is an array, you may want to add an $unwind stage
to your pipeline. Otherwise, the equality condition between the
localField and foreignField is foreignField: { $in: [
localField.elem1, localField.elem2, ... ] }.
So to join each local field array element with foreign field element you have to $unwind the local array.
db.content.aggregate([
{"$unwind":"$casts"},
{"$lookup":{"from":"casts","localField":"casts._id","foreignField":"_id","as":"_casts"}}
])
Vendor Collection
Items Collection
db.items.aggregate([
{ $match:
{"item_id":{$eq:"I001"}}
},
{
$lookup:{
from:"vendor",
localField:"vendor_id",
foreignField:"vendor_id",
as:"vendor_details"
}
},
{
$unwind:"$vendor_details"
},
{
$project:{
"_id":0,
"vendor_id":0,
"vendor_details.vendor_company_description":0,
"vendor_details._id":0,
"vendor_details.country":0,
"vendor_details.city":0,
"vendor_details.website":0
}
}
]);
Output
Your Casts collection shows only 1 document. Your Contents collection, likewise, shows only 1 document.
This is 1 to 1 - not 1 to 2. Aggregate is working as designed.
The Contents document has 2 "casts." These 2 casts are sub-documents. Work with those as sub-documents, or re-design your collections. I don't like using sub-documents unless I know I will not need to use them as look-ups or join on them.
I would suggest you re-design your collection.
Your Contents collection (it makes me think of "Movies") could look like this:
_id
title
releaseDate
genre
etc.
You can create a MovieCasts collection like this:
_id
movieId (this is _id from Contents collection, above)
castId (this is _id from Casts collection, below)
Casts
_id
name
age
etc.

how to get last element present in array in mongodb using golang?

I'm working in go language. I'm using mgo driver to get the data from mongodb. I want last entry from the events array.
There will be huge data in future. so I don't want to read the whole record but just want specific data from the record.
db.events.find({"_id":"59ce53b9-970a-44a2-8419-b41a99120b25"},{"events":{$slice:-1}}).pretty()
this is working in mongo shell. I want this to work in go lang.
This is the sample data, from which I want last entry present in events.
{
"_id" : "59ce53b9-970a-44a2-8419-b41a99120b25",
"version" : 9,
"events" : [
{
"event_type" : "customer:added",
"data" : {
"id" : "59ce53b9-970a-44a2-8419-b41a99120b25",
"name" : "arjun"
},
"timestamp" : ISODate("2017-11-20T12:21:34.910Z"),
"aggregate_type" : "customer",
"_id" : "59ce53b9-970a-44a2-8419-b41a99120b25",
"version" : 1
},
{
"event_type" : "customer:address-updated",
"data" : {
"id" : "59ce53b9-970a-44a2-8419-b41a99120b25",
"address" : "bangalore"
},
"timestamp" : ISODate("2017-11-20T12:22:08.496Z"),
"aggregate_type" : "customer",
"_id" : "59ce53b9-970a-44a2-8419-b41a99120b25",
"version" : 2
}
]
}
What you pass as the 2nd argument to find() is a projection.
Projections in mgo can be specified using the Query.Select() method.
So your query in mgo simply looks like this:
sess := ... // Acquire MongoDB session
c := sess.DB("dbname").C("events")
var doc bson.M
err := c.FindId("59ce53b9-970a-44a2-8419-b41a99120b25").
Select(bson.M{"events": bson.M{"$slice": -1}}).
One(&doc)
if err != nil {
// Handle error
}
fmt.Println(len(doc["events"].([]interface{}))) // This prints 1
fmt.Println(doc)

ReactiveMongo: Projection element not return using reactive mongo query

i have following mongodb document:
{
"_id" : ObjectId("5592c0e6ea16e552ac90e169"),
-----------
"location" : {
"_id" : ObjectId("5592c17fc3ad8cbffa0e9778"),
"companyFieldId" : ObjectId("559140f1ea16e552ac90e058"),
"name" : "Location",
"alias" : "Points",
"locations" : [
{
"_id" : ObjectId("5592c17fc3ad8cbffa0e9779"),
"country" : "India",
"state" : "Punjab",
"city" : "Moga",
"zip" : "142001",
"custom" : false
},
{
"_id" : ObjectId("5592c17fc3ad8cbffa0e977a"),
"country" : "India da address",
"custom" : true
}
],
"mandatory" : true,
"allowForGroups" : false
},
-----------
}
When i query the document using following query:
companyCollection.find($doc("_id" $eq companyId, "location._id" $eq locationId)).projection($doc("location" -> 1, "_id" -> 1)).cursor[LocationField].headOption;
It will return only company id. But when i change the projection value to projection($doc("location" -> 1, "_id" -> 0)) it return empty document. I am using Query DSL for write the queries.
UPDATE
When i create query like:
companyCollection.find($doc("_id" $eq companyId, "department._id" $eq departmentId), $doc("department" -> 1, "_id" -> 0)).cursor[Company].headOption
with this my return value is map with Company and with its property LocationField using projection and rest of the fields are ignore by mongodb. But my basic requirement is return only location inner document value and map with LocationField. When i run query in mongo db console like :
db.companies.find({"_id": ObjectId('5592c0e6ea16e552ac90e169'), "location._id": ObjectId('5592c17fc3ad8cbffa0e9778')}, {"location": 1, "_id": 0})
The result behavior is same as my reactive mongo query. Is it possible with mongo db for return only inner document, instead of full document structure?

How to update particular array element in MongoDB

I am newbie in MongoDB. I have stored data inside mongoDB in below format
"_id" : ObjectId("51d5725c7be2c20819ac8a22"),
"chrom" : "chr22",
"pos" : 17060409,
"information" : [
{
"name" : "Category",
"value" : "3"
},
{
"name" : "INDEL",
"value" : "INDEL"
},
{
"name" : "DP",
"value" : "31"
},
{
"name" : "FORMAT",
"value" : "GT:PL:GQ"
},
{
"name" : "PV4",
"value" : "1,0.21,0.00096,1"
}
],
"sampleID" : "Job1373964150558382243283"
I want to update the value to 11 which has the name as Category.
I have tried below query:
db.VariantEntries.update({$and:[ { "pos" : 117199533} , { "sampleID" : "Job1373964150558382243283"},{"information.name":"Category"}]},{$set:{'information.value':'11'}})
but Mongo replies
can't append to array using string field name [value]
How one can form a query which will update the particular value?
You can use the $ positional operator to identify the first array element to match the query in the update like this:
db.VariantEntries.update({
"pos": 17060409,
"sampleID": "Job1373964150558382243283",
"information.name":"Category"
},{
$set:{'information.$.value':'11'}
})
In MongoDB you can't adress array values this way. So you should change your schema design to:
"information" : {
'category' : 3,
'INDEL' : INDEL
...
}
Then you can adress the single fields in your query:
db.VariantEntries.update(
{
{"pos" : 117199533} ,
{"sampleID" : "Job1373964150558382243283"},
{"information.category":3}
},
{
$set:{'information.category':'11'}
}
)