$set an embedded value in collection? - mongodb

I have a document like so:
{
"_id" : "243kAaNRsEvhrguNs",
"createdAt" : ISODate("2015-04-07T16:43:15.299Z"),
"profile" : {
"balance" : 9.71,
"deposited" : 0,
"withdrawn" : 30,
"virgin" : false,
"won" : 29.709999999999997,
"taxable" : false
}
}
and I want to add a field in "profile" called (say) "test". I've tried:
db.users.find({"_id": "243kAaNRsEvhrguNs"},{$set: {"profile.test": "false"}})
but this doesn't seem to work. Can someone help?
EDIT:
Figured it out, was really stupid. This works:
db.users.update({"_id": "243kAaNRsEvhrguNs"},{$set: {"profile.test": "false"}}

Related

Get all objects where a property matches a value nested in array

I have the following data table:
{
"_id" : ObjectId("value"),
"owner" : "testuser",
"date" : ISODate("2017-03-16T12:45:03.386Z"),
"location" : "thuis",
"venue" : "bijna thuis",
"description" : "fghgfh",
"completed" : false,
"winnerName" : null,
"subscriptions" : [],
"interactions" : [
{
"_id" : ObjectId("objectid"),
"owner" : "testuser",
"type" : "guess",
"date" : ISODate("2017-03-06T12:13:10.049Z"),
"answer" : false,
"message" : "test 1"
},
{
"_id" : ObjectId("objectid"),
"owner" : "testuser",
"type" : "guess",
"date" : ISODate("2017-03-06T12:13:10.049Z"),
"answer" : false,
"message" : "test 2"
}
],
"__v" : 0,
"active" : true
}
The above is just one game object. Which means we got several of this objects in our database.
I am trying to get only the interactions where the owner == "testuser".
The problem is that I cannot seem to figure out the best way to do this.
In my code I got 2 objects ( Game & Interaction) where Game has an array of interactions.
Is there someway I can still do this using the mongocsharpdriver.
Thanks in advance for all the help.
Hope it work for you Thanks :-)
collection.Find(x => x.owner == "testuser").ToList(); //where collection is MongoDB collection
Thanks for all the suggestions and sorry for the late response. But I find a way to solve it like this:
var filter = Builders<Game>.Filter.ElemMatch("interactions",
Builders<Interaction>.Filter.Eq("owner", owner));
var interactions = await MongoCollection.Find(filter).ToListAsync();
return interactions.SelectMany(item => item.Interactions).ToList();
This will it will return all the interactions that has a certain user as owner.
Hope I can help somebody out with this answer.

Mongoid query embedded document and return parent

I have this document, each is a tool:
{
"_id" : ObjectId("54da43aea96ddcc40915a457"),
"checked_in" : false,
"barcode" : "PXJ-234234",
"calibrations" : [
{
"_id" : ObjectId("54da46ec546173129d810100"),
"cal_date" : null,
"cal_date_due" : ISODate("2014-08-06T00:00:00.000+0000"),
"time_in" : ISODate("2015-02-10T17:46:20.250+0000"),
"time_out" : ISODate("2015-02-10T17:46:20.250+0000"),
"updated_at" : ISODate("2015-02-10T17:59:08.796+0000"),
"created_at" : ISODate("2015-02-10T17:59:08.796+0000")
},
{
"_id" : ObjectId("5509e815686d610b70010000"),
"cal_date_due" : ISODate("2015-03-18T21:03:17.959+0000"),
"time_in" : ISODate("2015-03-18T21:03:17.959+0000"),
"time_out" : ISODate("2015-03-18T21:03:17.959+0000"),
"cal_date" : ISODate("2015-03-18T21:03:17.959+0000"),
"updated_at" : ISODate("2015-03-18T21:03:17.961+0000"),
"created_at" : ISODate("2015-03-18T21:03:17.961+0000")
},
{
"_id" : ObjectId("5509e837686d610b70020000"),
"cal_date_due" : ISODate("2015-03-18T21:03:51.189+0000"),
"time_in" : ISODate("2015-03-18T21:03:51.189+0000"),
"time_out" : ISODate("2015-03-18T21:03:51.189+0000"),
"cal_date" : ISODate("2015-03-18T21:03:51.189+0000"),
"updated_at" : ISODate("2015-03-18T21:03:51.191+0000"),
"created_at" : ISODate("2015-03-18T21:03:51.191+0000")
}
],
"group" : "Engine",
"location" : "Here or there",
"model" : "ZX101C",
"serial" : NumberInt(15449),
"tool" : "octane analyzer",
"updated_at" : ISODate("2015-09-30T20:43:55.652+0000"),
"description" : "Description...",
}
Tools are calibrated periodically. What I want to do is grab tools that are due this month.
Currently, my query is this:
scope :upcoming, -> { where(:at_ats => false).where('calibrations.0.cal_date_due' => {'$gte' => Time.now-1.day, '$lte' => Time.now+30.days}).order_by(:'calibrations.cal_date_due'.asc) }
However, this query gets the tool by the first calibration object and it needs to be the last. I've tried a myriad of things, but I'm stuck here.
How can I make sure I'm querying the most recent calibration document, not the first (which would be the oldest and therefore not relevant)?
You should look into aggregation framework and $unwind operator.
This link may be of help.
This link may be helpful. It contains an example of use of 'aggregation framework' for get the last element of the array, that is, the most recent in your case.

$push removes all other fields in the document

I try to update a field in a collection that contains an array with $push. Instead of adding the value, the document gets replaced by a document containing only _id. If I do the update in the mongo-console it works.
Here's the code: (Serverside)
Meteor.methods({
dismiss: function (jobId,userId) {
Jobs.update(jobId, {$push : {dismissed: userId}},{validate: false},function(){});
},
});
The document in mongodb before looks like this:
{ "_id" : "MBfQ39BsKwqspLLEL", "title" : "Derniset edolar ingreadcomi permaap manthe soi ti.", "description" : "Siter tersion ingtery enlaringvi disicgen yma.", "wage" : 10, "wagePeriod" : "hour", "currency" : "Euro", "image" : "xGDcPNXjn7kpa2mv2", "createdAt" : ISODate("2015-06-18T06:40:47.575Z") }
And after the operation it looks like this:
{ "_id" : "MBfQ39BsKwqspLLEL" }
Any help appreciated.
Thanks.

Mongodb + Mongoose: trying to add a sub-sub-item

Does this makes any sense when trying to add a sub-sub-item? (I'm new to mongo - be merciful :-))
question = db.questions.findOne({_id: ObjectId("529c5d44211c9a8c11000006")})
question.answers[0].votes.insert(...)
When I run this from the mongo console the result is an error saying [object object] does not have the method insert.
I have the following mongoDB Question Schema.
{
"__v" : 2,
"_creator" : ObjectId("529c5d2d211c9a8c11000005"),
"_id" : ObjectId("529c5d44211c9a8c11000006"),
"answers" : [
{
"postDate" : ISODate("2013-12-02T10:14:19.060Z"),
"postDateText" : "15min ago",
"authorEmail" : "guys#pix.com",
"authorName" : "guys#pix.com",
"body" : "You need magic powder",
"isWinner" : false,
"_creator" : ObjectId("529c5d2d211c9a8c11000005"),
"_id" : ObjectId("529c5d7b211c9a8c11000008"),
"votes" : [
{
"voteType" : "up",
"_creator" : ObjectId("529c5d2d211c9a8c11000005"),
"_id" : ObjectId("529c5d5b211c9a8c11000007")
}
]
}
],
"authorEmail" : "guys#wix.com",
"authorName" : "guys#wix.com",
"body" : "I'm trying to fly...\n\n<pre class=\"brush: js;\">\nfunction logName(name) {\n console.log(name);\n}\n</pre>",
"isResolved" : false,
"postDate" : ISODate("2013-12-02T10:13:24.235Z"),
"tags" : [
"fly"
],
"title" : "How do I fly?",
"views" : [],
"votes" : [
{
"voteType" : "up",
"_creator" : ObjectId("529c5d2d211c9a8c11000005"),
"_id" : ObjectId("529c5d5b211c9a8c11000007")
}
]
}
I'm trying, given a questionId and an answerId to add a vote to the votes array (which is inside the answer). I can't seem to do it. Help?
insert is for adding whole new documents; when you just want to add a new element to an array field of an existing document, you can use update along with an operator like $push.
So, in the shell you would use something like this:
db.questions.update(
{_id: ObjectId("529c5d44211c9a8c11000006")},
{'answers.0.votes': {$push: voteToPush}})

In MongoDB, how to filter by location, sort by another field and paginate the results correctly?

When i don't use pagination, everything works fine (i have only 3 records in this collection, so all of them are listed here):
db.suppliers.find({location: {$near: [-23.5968323, -46.6782386]}},{name:1,badge:1}).sort({badge:-1})
{ "_id" : ObjectId("4f33ff549112b9b84f000070"), "badge" : 3, "name" : "Dedetizadora Alvorada" }
{ "_id" : ObjectId("4f33ff019112b9b84f00005b"), "badge" : 2, "name" : "Sampex Desentupidora e Dedetizadora" }
{ "_id" : ObjectId("4f33feae9112b9b84f000046"), "badge" : 1, "name" : "Higitec Desentupimento e Dedetização" }
But when i try to paginate from the first to the second page, one record doesn't show up and one is repeated:
db.suppliers.find({location: {$near: [-23.5968323, -46.6782386]}},{name:1,badge:1}).sort({badge:-1}).skip(0).limit(2)
{ "_id" : ObjectId("4f33ff549112b9b84f000070"), "badge" : 3, "name" : "Dedetizadora Alvorada" }
{ "_id" : ObjectId("4f33feae9112b9b84f000046"), "badge" : 1, "name" : "Higitec Desentupimento e Dedetização" }
db.suppliers.find({location: {$near: [-23.5968323, -46.6782386]}},{name:1,badge:1}).sort({badge:-1}).skip(2).limit(2)
{ "_id" : ObjectId("4f33feae9112b9b84f000046"), "badge" : 1, "name" : "Higitec Desentupimento e Dedetização" }
Am i doing something wrong or is this some kind of bug?
edit:
Here is a workaround for this. Basically you shouldn't mix $near queries with sorting; use $within instead.
There is an open issue regarding the same problem. Please have a look & vote Geospatial result paging fails when sorting with additional keys