Mongo Command LIne Querying Embedded Document by Object Id - mongodb

I have following in my accounts collection:
{ "_id" : ObjectId("4fc55125476e0a27d9000003"),
"created_at" : ISODate("2012-05-29T22:43:49Z"),
"teachers" : [ {
"_id" : ObjectId("4fc55125476e0a27d9000004"),
"updated_at" : ISODate("2012-05-29T22:43:49Z"),
"created_at" : ISODate("2012-05-29T22:43:49Z")
} ],
"updated_at" : ISODate("2012-05-29T22:43:49Z")
}
I want to query for an account that has a teacher with _id 4fc55125476e0a27d9000003.
If I use the command
db.accounts.findOne({"teachers._id" : ObjectId("4fc55125476e0a27d9000004")})
it returns null.
Also, why does the mongo command line thing hang when I use find instead of findOne with the above command.

As others pointed out, the query actually works. Not sure what was going on the other day that I couldn't get it to return the correct result. Maybe I was using an incorrect db. Thanks for the help and apologies for wasting your time.

Related

Mongodo db delete documents between custom fields

I have below documents in mongodb, am trying to delete the documents based on the referenceId field between the values X0000000005 and X00000000010, I couldnt find any articles for deleting mongo documents based on custom field, can someone please help me to do this deletion if its possible?
{
"_id" : ObjectId("5a0f13ad0a83924b84d16b7d"),
"senderId" : "783",
"clientId" : "146196",
"referenceId" : "X00000000001",
"file" : "jAAAAAECAAABaAAAAKQAAJyMKYqPYvFQKJrZ/fqYjDKNdXdOMK58tPQ"
}
{
"_id" : ObjectId("5a0f13ad0a83924b84d16b7e"),
"senderId" : "783",
"clientId" : "146196",
"referenceId" : "X00000000002",
"file" : "jAAAAAECAAABaAAAAKQAAJyMKYqPYvFQKJrZ/fqYjDKNdXdOMK58tPQ"
}
.
.
.
.
.
.
{
"_id" : ObjectId("5a0f13ad0a83924b84d16b7f"),
"senderId" : "783",
"clientId" : "146196",
"referenceId" : "X00000000020",
"file" : "jAAAAAECAAABaAAAAKQAAJyMKYqPYvFQKJrZ/fqYjDKNdXdOMK58tPQ"
}
The following simple query should work:
db.collection.remove({"referenceId":{$gte:"X00000000005"}, "referenceId":{$lte:"X00000000010"}})
You might want to run a find() using the same filter first in order to make sure that the delete() will affect the right records. That'd obviously be this then:
db.collection.find({"referenceId":{$gte:"X00000000005"}, "referenceId":{$lte:"X00000000010"}})
Also, depending on the exact definition of your
between the values X0000000005 and X00000000010
you might need to swap the $lte and $gte operators out for something else ($gt and/or $lt).
db.collection.remove({"referenceId": {"$lte": "X00000000010", "gte": "X0000000005"}})

MongoEngine delete dict key from object field

I have a pretty complex Flask website with lots of DB interaction but have got stuck with a seemingly simple delete function!
I am trying to delete key 56 from sensordict in the (simplified) SiteConfig document below using MongoEngine
{
"_id" : "12345",
"sensordict" : {
"56" : {
"currentval" : 1.2,
"devicetype" : NumberInt(2)
},
"70" : {
"currentval" : 31.0,
"devicetype" : NumberInt(2)
}
},
"siteserial" : "45678",
"status" : NumberInt(1)
}
Code tried below where sensorid = '56':
def delete_sensor(siteconfig, sensorid):
dbsite = SiteConfig.objects(id=siteconfig.id).first()
dbsite.update(unset__sensordict__S=sensorid)
dbsite.save()
The code is failing at the update with mongoengine.errors.OperationError: Update failed (The positional operator did not find the match needed from the query. Unexpanded update: sensordict.$)
I suspect this is a simple one but have been way down the rabbit hole for a couple of hours on this one and any help would be much appreciated
Thanks
Bill
dbsite.update(unset__sensordict__S=sensorid) should be dbsite.update(unset__sensordict__56=1) since you have to unset the field with key '56'. This should work

I have big database on mongodb and can't find and use my info

This my code:
db.test.find() {
"_id" : ObjectId("4d3ed089fb60ab534684b7e9"),
"title" : "Sir",
"name" : {
"_id" : ObjectId("4d3ed089fb60ab534684b7ff"),
"first_name" : "Farid"
},
"addresses" : [
{
"city" : "Baku",
"country" : "Azerbaijan"
},{
"city" : "Susha",
"country" : "Azerbaijan"
},{
"city" : "Istanbul",
"country" : "Turkey"
}
]
}
I want get output only all city. Or I want get output only all country. How can i do it?
I'm not 100% about your code example, because if your 'find' by ID there's no need to search by anything else... but I wonder whether the following can help:
db.test.insert({name:'farid', addresses:[
{"city":"Baku", "country":"Azerbaijan"},
{"city":"Susha", "country":"Azerbaijan"},
{"city" : "Istanbul","country" : "Turkey"}
]});
db.test.insert({name:'elena', addresses:[
{"city" : "Ankara","country" : "Turkey"},
{"city":"Baku", "country":"Azerbaijan"}
]});
Then the following will show all countries:
db.test.aggregate(
{$unwind: "$addresses"},
{$group: {_id:"$country", countries:{$addToSet:"$addresses.country"}}}
);
result will be
{ "result" : [
{ "_id" : null,
"countries" : [ "Turkey", "Azerbaijan"]
}
],
"ok" : 1
}
Maybe there are other ways, but that's one I know.
With 'cities' you might want to take more care (because I know cities with the same name in different countries...).
Based on your question, there may be two underlying issues here:
First, it looks like you are trying to query a Collection called "test". Often times, "test" is the name of an actual database you are using. My concern, then, is that you are trying to query the database "test" to find any collections that have the key "city" or "country" on any of the internal documents. If this is the case, what you actually need to do is identify all of the collections in your database, and search them individually to see if any of these collections contain documents that include the keys you are looking for.
(For more information on how the db.collection.find() method works, check the MongoDB documentation here: http://docs.mongodb.org/manual/reference/method/db.collection.find/#db.collection.find)
Second, if this is actually what you are trying to do, all you need to for each collection is define a query that only returns the key of the document you are looking for. If you get more than 0 results from the query, you know documents have the "city" key. If they don't return results, you can ignore these collections. One caveat here is if data about "city" is in embedded documents within a collection. If this is the case, you may actually need to have some idea of which embedded documents may contain the key you are looking for.

Updating MongoDB object field

I have searched and tried many answers but I can't seem to get this working. I have a user in MongoDB (db.users...) and I'm trying to update a field titled 'role' in one particular document. If I perform a :
db.users.find();
I get:
{ "_id" : "fDx2g34G8vxsDu3vf", "createdAt" : ISODate("2014-06-03T16:31:47.382Z"),
"emails" : [ { "address" : "andrewmlarking#gmail.com", "verified" : false } ],
"profile" : { "name" : "Admin", "role" : "user", "division" : "0", "enrolled" : "false" },
"services" : { "password" : { "srp" : { "identity" "dEad06c_5mjzsprUzgRyh6tB66OiaybdLzbnxFzO1xh",
"salt" : "zqWsh etc etc
Which is fine, if I then perform a:
db.users.update({_id:"2xnoy3jqcHCaFp7Br"}, { role:"admin"});
I get a:
assert failed : need an object Error: Printing Stack Trace
at printStackTrace (src/mongo/shell/utils.js:37:15)
at doassert (src/mongo/shell/assert.js:6:5)
at assert (src/mongo/shell/assert.js:14:5)
at DBCollection.update (src/mongo/shell/collection.js:220:5)
at (shell):1:10
Any ideas?
Thanks.
First of all if you are trying to update the role field of the profile subdocument your syntax is off. It should be:
db.users.update({_id:"2xnoy3jqcHCaFp7Br"}, {$set: { "profile.role":"admin"}})
Otherwise you will just delete all the other fields of the document.
Regarding the error message, that normally only occurs when you run update with a single argument (the query) without the fields to update. Are you sure you are calling it as documented in your question?
Regardless I would highly advise you to review MongoDB documentation for updates:
http://docs.mongodb.org/manual/tutorial/modify-documents/
Maybe you should try adding ObjectId to the query.
Also, as pointed by #John Petrone you should use $set
I usually do
db.users.update({_id:ObjectId("2xnoy3jqcHCaFp7Br")}, {$set: { "profile.role":"admin"});

MongoDB : query result size greater than collection size

I'm analyzing a MongoDB data source to check its quality.
I'm wondering if every document contains the attribute time: so I used this two command
> db.droppay.find().count();
291822
> db.droppay.find({time: {$exists : true}}).count()
293525
How can I have more elements with a given field than the elements contained in whole collection ? What's going wrong ? I'm unable to find the mistake.
If it's necessary I can post you the expected structure of the document.
Mongo Shell version is 1.8.3. Mongo Db version is 1.8.3.
Thanks in advance
This is the expected structure of the document entry:
{
"_id" : ObjectId("4e6729cc96babe974c710611"),
"action" : "send",
"event" : "sent",
"job_id" : "50a1b7ac-7482-4ad6-ba7d-853249d6a123",
"result_code" : "0",
"sender" : "",
"service" : "webcontents",
"service_name" : "webcontents",
"tariff" : "0",
"time" : "2011-09-07 10:22:35",
"timestamp" : "1315383755",
"trace_id" : "372",
"ts" : "2011-09-07 09:28:42"
}
My guess is that is an issue with the index. I bet that droppay has an index on :time, and some unsafe operation updated the underlying collection without updating the index.
Can you try repairing the db, and see if that makes it better.
Good luck.
There are probably time values that are of type array.
You may do db.droppay.find({time: {$type : 4}}) to find such documents.