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

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)

Related

And Operator in Criteria not working as expected for nested documents inside aggregation Spring Data Mongo

I am trying to fetch total replies where read values for a replies is true. But I am getting count value as 3 but expected value is 2 (since only two read value is true) through Aggregation function available in Spring Data Mongo. Below is the code which I wrote:
Aggregation sumOfRepliesAgg = newAggregation(match(new Criteria().andOperator(Criteria.where("replies.repliedUserId").is(userProfileId),Criteria.where("replies.read").is(true))),
unwind("replies"), group("replies").count().as("repliesCount"),project("repliesCount"));
AggregationResults<Comments> totalRepliesCount = mongoOps.aggregate(sumOfRepliesAgg, "COMMENTS",Comments.class);
return totalRepliesCount.getMappedResults().size();
Using AND Operator inside Criteria Query and passed two criteria condition but not working as expected. Below is the sample data set:
{
"_id" : ObjectId("5c4ca7c94807e220ac5f7ec2"),
"_class" : "com.forum.api.domain.Comments",
"comment_data" : "logged by karthe99",
"totalReplies" : 2,
"replies" : [
{
"_id" : "b33a429f-b201-449b-962b-d589b7979cf0",
"content" : "dasdsa",
"createdDate" : ISODate("2019-01-26T18:33:10.674Z"),
"repliedToUser" : "#karthe99",
"repliedUserId" : "5bbc305950a1051dac1b1c96",
"read" : false
},
{
"_id" : "b886f8da-2643-4eca-9d8a-53f90777f492",
"content" : "dasda",
"createdDate" : ISODate("2019-01-26T18:33:15.461Z"),
"repliedToUser" : "#karthe50",
"repliedUserId" : "5c4bd8914807e208b8a4212b",
"read" : true
},
{
"_id" : "b56hy4rt-2343-8tgr-988a-c4f90598h492",
"content" : "dasda",
"createdDate" : ISODate("2019-01-26T18:33:15.461Z"),
"repliedToUser" : "#karthe50",
"repliedUserId" : "5c4bd8914807e208b8a4212b",
"read" : true
}
],
"last_modified_by" : "karthe99",
"last_modified_date" : ISODate("2019-01-26T18:32:41.394Z")
}
What is the mistake in the query that I wrote?

MongoDB + Laravel fetch value if field exists in array otherwise fetch value from another field in array

I am working with laravel 5.3 and jenssegers-mongodb.
I have following document in MongoDB :
{
"_id" : ObjectId("590fgfhddfgdfgdfgdg"),
"name" : {
"en" : "Meeting",
"gu" : "બેઠક"
},
},
{
"_id" : ObjectId("590fgfhddfgdfgdfgdg"),
"name" : {
"en" : "All",
},
}
I would like to fetch value if (name.gu) is exist, otherwise fetch from (name.en).
Is it possible ?

How can I use mongodb projections with Go and mgo?

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)

MongoDb - Query for specific subdocument

I have a set of mongodb documents with the following structure:
{
"_id" : NUUID("58fbb893-dfe9-4f08-a761-5629d889647d"),
"Identifiers" : {
"IdentificationLevel" : 2,
"Identifier" : "extranet\\test#test.com"
},
"Personal" : {
"FirstName" : "Test",
"Surname" : "Test"
},
"Tags" : {
"Entries" : {
"ContactLists" : {
"Values" : {
"0" : {
"Value" : "{292D8695-4936-4865-A413-800960626E6D}",
"DateTime" : ISODate("2015-04-30T09:14:45.549Z")
}
}
}
}
}
}
How can I make a query with the mongo shell which finds all documents with a specific "Value" (e.g.{292D8695-4936-4865-A413-800960626E6D} in the Tag.Entries.ContactLists.Values path?
The structure is unfortunately locked by Sitecore, so it is not an options to use another structure.
As your sample collection structure show Values is object, it contains only one Value. Also you must check for Value as it contains extra paranthesis. If you want to get Value from given structure try following query :
db.collection.find({
"Tags.Entries.ContactLists.Values.0.Value": "{292D8695-4936-4865-A413-800960626E6D}"
})

mongodb get elements which was inserted after some document

I have a document and I need to query mongodb database to return me all the documents which was inserted after current document.
Is it possible and how to do that query?
If you do not override the default _id field you can use that objectID (see the mongodb docs) to make a comparison by time. For instance, the following query will find all the documents that are inserted after curDoc has been inserted (assuming none overwrite the _id field):
>db.test.find({ _id : {$gt : curDoc._id}})
Note that these timestamps are not super granular, if you would like a finer grained view of the time that documents are inserted I encourage you to add your own timestamp field to the documents you are inserting and use that field to make such queries.
If you are using Insert time stamp as on of the parameter, you can query like below
> db.foo.find()
{ "_id" : ObjectId("514bf8bbbe11e483111af213"), "Name" : "abc", "Insert_time" : ISODate("2013-03-22T06:22:51.422Z") }
{ "_id" : ObjectId("514bf8c5be11e483111af214"), "Name" : "xyz", "Insert_time" : ISODate("2013-03-22T06:23:01.310Z") }
{ "_id" : ObjectId("514bf8cebe11e483111af215"), "Name" : "pqr", "Insert_time" : ISODate("2013-03-22T06:23:10.006Z") }
{ "_id" : ObjectId("514bf8eabe11e483111af216"), "Name" : "ijk", "Insert_time" : ISODate("2013-03-22T06:23:38.410Z") }
>
Here my Insert_time corresponds to the document inserted time, and following query will give you the documents after a particular Insert_time,
> db.foo.find({Insert_time:{$gt:ISODate("2013-03-22T06:22:51.422Z")}})
{ "_id" : ObjectId("514bf8c5be11e483111af214"), "Name" : "xyz", "Insert_time" : ISODate("2013-03-22T06:23:01.310Z") }
{ "_id" : ObjectId("514bf8cebe11e483111af215"), "Name" : "pqr", "Insert_time" : ISODate("2013-03-22T06:23:10.006Z") }
{ "_id" : ObjectId("514bf8eabe11e483111af216"), "Name" : "ijk", "Insert_time" : ISODate("2013-03-22T06:23:38.410Z") }
>