Meteor/MongoDB order by - mongodb

I have the following schema
{
"_id" : "PbSkep5Auv9ZBeEyR",
"item" : "Footage",
"permalink" : "footage",
"itemIndex" : 23,
}
When I paste them in my remote DB it order them by _id, which seems to be a automatic meteor key. I am using robomongo and am trying to reorder the items by 'itemIndex'. How do I do this?

robomongo or other UI have nothing to do with the order of the data: you need to specify this in your query.
lookup the Mongo documentation:
db.collection.find({}).sort( { itemIndex: -1 } )
or
db.collection.find( { $query: {}, $orderby: { itemIndex : -1 } } )
http://docs.mongodb.org/v3.0/reference/operator/meta/orderby/

Related

check if value exists in array field in mongodb

I want to check if user id exists inside an array field of mongodb (using meteor)
db.posts.find().pretty()
{
"_id" : "hT3ezqEyTaiihoh6Z",
"body" : "hey\n",
"authorId" : "AyJo5nf2Lkdqd6aRh",
"createdAt" : ISODate("2016-05-13T06:19:34.726Z"),
"updatedAt" : ISODate("2016-05-13T06:19:34.726Z"),
"likecount" : 0,
"already_voted" : [ ] }
db.posts.find( { _id:"hT3ezqEyTaiihoh6Z"},{ already_voted: { $in : ["AyJo5nf2Lkdqd6aRh"]} }).count()
1
It gives count value 1 , where as I am expecting it to be 0 .
Your logic is fine. Just the syntax is wrong.
db.posts
.find({
_id: "hT3ezqEyTaiihoh6Z",
already_voted: { $in: ["AyJo5nf2Lkdqd6aRh"] },
})
.count();
This should work.
You can just simply use count method. Don't need to use two operation like Find and then count.
db.posts
.count({
_id: "hT3ezqEyTaiihoh6Z",
already_voted: { $in: ["AyJo5nf2Lkdqd6aRh"] }
});

mongodb update field a to be value of field b

I am trying to run a mongo query to update the value of one field with the value of another field. I have the following documents:
{ "_id" : ObjectId("56e0a3a2d59feaa43fba49d5"), "old" : 16, "new" : 17 }
{ "_id" : ObjectId("56e0a3a2d59feaa43fba49d3"), "old" : 11, "new" : 12 }
I would like to make it look like this after update:
{ "_id" : ObjectId("56e0a3a2d59feaa43fba49d5"), "old" : 16, "new" : 16 }
{ "_id" : ObjectId("56e0a3a2d59feaa43fba49d3"), "old" : 11, "new" : 11 }
I've tried the following with no luck
db.runCommand(
{
findAndModify: "testData",
query: { $where: "this.new != this.old" },
update: { old : this.new },
upsert: true
}
)
and
db.testData.update( { $where: "this.new != this.old" }, { $set: { old: this.new } } );
Is this even possible with mongoDb?
I would like to do it in a single query and not iterate through each document.
Any ideas would be greatly appreciated.
Thank you
You can try something like this and probably change _id when you want to update other document:
db.testData.find().forEach(function(elem) {
db.testData.update({
"_id": "56e0a3a2d59feaa43fba49d5"
}, {
$set: {
new: elem.old
}
});
});
You can't do that in MongoDB yet (note to visitors from the future: I'm referring to V3.2).
You have to iterate on the documents.
NB there's a trick in case you don't mind deleting the old field: use rename to rename old to new.
NB2 for some SQLike-fu actions (not this one) the aggregation framework can be useful.

How can we achieve "Select For Update" in Mongodb?

Below is my sample document. I wanted to load this document & read total_comments value & perform certain logic on it and update the document again with new total_comments value. How should I ensure total_comments value is not updated by some other request before I complete my above explained steps?
{ "_id" : ObjectId("56782a933d5c6ca02100002b"), "total_comments" : 12, "time_updated" : 1450715963 }
In mysql, we can do it by doing "select for update"?. How can we achieve this in Mongodb?.
Here is my MongoDB version:
> db.version()
3.0.7
Here is my storage engine details:
> db.serverStatus().storageEngine
{ "name" : "mmapv1" }
Use findAndModify() to update a document.
For example you can increment total_comments by 1 with
db.collection.findAndModify({
_id: ObjectId("56782a933d5c6ca02100002b")
}, {}, {
$inc: { "total_comments": 1 }
});

mongodb update and/or change an array key without using the value

I'm having trouble removing/renaming an array object from my mongodb.
{
"_id" : ObjectId("556a7e1b7f0a6a8f27e01b8a"),
"accountid" : "AC654164545",
"sites" :[
{ "site_id" : "example1.com" },
{ "002" : "example2.com" },
{ "003" : "example3.com" },
{ "004" : "example4.com" },
{ "005" : "example5.com" },
{ "006" : "example6.com" }
]}
}
Please take notice of the array key "site_id", I want to change it to "001" by either removing and appending it, which I know how to do, or rename it.
I've tried:
db.accounts.update({'id':ObjectId("556a7e1b7f0a6a8f27e01b8a")}, {$unset: {sites.site_id}})
But that says "unexpected token".
So I tried:
db.accounts.update({'id':ObjectId("556a7e1b7f0a6a8f27e01b8a")}, {$unset: {sites:site_id}})
That says "site_id is not defined"
Then I tried:
db.accounts.update({'id':ObjectId("556a7e1b7f0a6a8f27e01b8a")}, {$unset: {sites:'site_id'}})
That says WriteResult({ "nMatched" : 0, "nUpserted" : 0, "nModified" : 0 })
I also tried a $rename command:
db.accounts.update( { _id:ObjectId("556a7e1b7f0a6a8f27e01b8a") }, { $rename: { "sites.site_id": "sites.001" } } )
But that gave me a "Cannot use part (sites of sites.site_id) to traverse the element"
One option would be to use .find(), iterate through and delete it. Save the undeleted ones into an object, and run an .insert() command, but I want to stay away from that if I have too.
This site talks about dynamic renaming: http://docs.mongodb.org/manual/reference/operator/update/positional/
Aka first you make a matching query and then you use the $ to match that to the index in the array.
Here's the query that'll accomplish what you want for the test data you provided:
db.accounts.update({'accountid':"AC654164545", "sites.site_id": "example1.com"}, {$set: {"sites.$": {'001': 'example1.com'}}})
It is not recommended to use dynamic values such as numbers as a key in document structure. This will be more difficult to query using such values.
You can use $set and $elemMatch to get result as following:
db.collection.update({
'_id': ObjectId("556a7e1b7f0a6a8f27e01b8a"),
"sites": {
$elemMatch: {
"site_id": "example1.com"
}
}
}, {
$set: {
"sites.$":{"001": "example1.com"}
}
})

mongo objectid 'contains' query

I would like to query a collection in a MongoDB database to find all records that contain a portion of an ObjectID. For a normal string I can use a regex like this:
db.teams.find({"some_string": /^51eed/})
But how would I do something similar on an ObjectID?
Specifically, I have a collection that looks something like this:
{ "status" : 0, "_id" : ObjectId("51e97ff613e737801d000002") }
{ "status" : 0, "_id" : ObjectId("51ee7513d1f7c57420000002") }
{ "status" : 0, "_id" : ObjectId("51eed9dd5b605af404000002") }
{ "status" : 0, "_id" : ObjectId("51eedab39108d8101c000002") }
I would like to query (in mongo) for all records where the ObjectId starts with "51eed". Your help is greatly appreciated.
You can simply do this with a range search, start at "51eed0000000000000000000" and end at "51eee0000000000000000000" (notice the "d" -> "e"):
db.teams.find( {
_id: {
$gte: ObjectId("51eed0000000000000000000"),
$lt: ObjectId("51eee0000000000000000000"),
}
} )
You could possibly just put that into a new ObjectId and fill the rest with 0's like:
db.teams.find({_id:{$gte:ObjectId("51eed0000000000000000000")}})
Should do the trick.