I am working on a project with Flask and Mongo DB and I want to display some embedded documents. I am not really getting error messages but the data is not displaying how I want it to. Currently, my documents look like this:
{ "_id" : ObjectId("590639009103ad05fd8555dc"),
"comments" : [ { "comment" :
"Hello World" } ],
"age" : 23,
"name" : "Mike" }
Now, I want to display data that will show the name and the comments that the individual said. I want something like this: Mike, says the following: 'Hello World'
My code looks like this:
thoughts = person.show()
for thought in thoughts:
print(thought["name"], "says the following:", thought["comments"])
where the show() method looks like this:
def show(self):
thoughts = self.db.people.find()
return thoughts
Now for the most part almost everything works how I want it to. When I run my code I get this:
Mike says the following: {'comment': 'Hello World'}
What I need to do is to dig further down into the embedded document to display:
Mike, says the following: 'Hello World'
I have tried the following:
for thought in thoughts:
print(thought["name"], "says the following:",
thought["comments.comment"])
which gets me the following error message: KeyError: 'comments.comment'
I then tried the following:
for thought in thoughts:
print(thought["name"], "says the following:", thought["comments"]
["comment"])
which gives me the following error:
TypeError: list indices must be integers, not str
Thus, I am somewhat stuck how to pull out each comment. Any help would be appreciated.
thought["comments"] is a list of dicts. you want the comment field of the first item on the list, thus:
print(thought["comments"][0]["comment"])
Related
I've found this question answered for C# and Perl, but not in the native interface. I thought this would work:
db.theColl.find( { _id: ObjectId("4ecbe7f9e8c1c9092c000027") } )
The query returned no results. I found the 4ecbe7f9e8c1c9092c000027 by doing db.theColl.find() and grabbing an ObjectId. There are several thousand objects in that collection.
I've read all the pages that I could find on the mongodb.org website and didn't find it. Is this just a strange thing to do? It seems pretty normal to me.
Not strange at all, people do this all the time. Make sure the collection name is correct (case matters) and that the ObjectId is exact.
Documentation is here
> db.test.insert({x: 1})
> db.test.find() // no criteria
{ "_id" : ObjectId("4ecc05e55dd98a436ddcc47c"), "x" : 1 }
> db.test.find({"_id" : ObjectId("4ecc05e55dd98a436ddcc47c")}) // explicit
{ "_id" : ObjectId("4ecc05e55dd98a436ddcc47c"), "x" : 1 }
> db.test.find(ObjectId("4ecc05e55dd98a436ddcc47c")) // shortcut
{ "_id" : ObjectId("4ecc05e55dd98a436ddcc47c"), "x" : 1 }
If you're using Node.js:
var ObjectId = require('mongodb').ObjectId;
var id = req.params.gonderi_id;
var o_id = new ObjectId(id);
db.test.find({_id:o_id})
Edit: corrected to new ObjectId(id), not new ObjectID(id)
Even easier, especially with tab completion:
db.test.find(ObjectId('4ecc05e55dd98a436ddcc47c'))
Edit: also works with the findOne command for prettier output.
You Have missed to insert Double Quotes.
The Exact Query is
db.theColl.find( { "_id": ObjectId("4ecbe7f9e8c1c9092c000027") } )
If you are working on the mongo shell, Please refer this : Answer from Tyler Brock
I wrote the answer if you are using mongodb using node.js
You don't need to convert the id into an ObjectId. Just use :
db.collection.findById('4ecbe7f9e8c1c9092c000027');
this collection method will automatically convert id into ObjectId.
On the other hand :
db.collection.findOne({"_id":'4ecbe7f9e8c1c9092c000027'}) doesn't work as expected. You've manually convert id into ObjectId.
That can be done like this :
let id = '58c85d1b7932a14c7a0a320d';
let o_id = new ObjectId(id); // id as a string is passed
db.collection.findOne({"_id":o_id});
I think you better write something like this:
db.getCollection('Blog').find({"_id":ObjectId("58f6724e97990e9de4f17c23")})
Once you opened the mongo CLI, connected and authorized on the right database.
The following example shows how to find the document with the _id=568c28fffc4be30d44d0398e from a collection called “products”:
db.products.find({"_id": ObjectId("568c28fffc4be30d44d0398e")})
I just had this issue and was doing exactly as was documented and it still was not working.
Look at your error message and make sure you do not have any special characters copied in. I was getting the error
SyntaxError: illegal character #(shell):1:43
When I went to character 43 it was just the start of my object ID, after the open quotes, exactly as I pasted it in. I put my cursor there and hit backspace nothing appeared to happen when it should have removed the open quote. I hit backspace again and it removed the open quote, then I put the quote back in and executed the query and it worked, despite looking exactly the same.
I was doing development in WebMatrix and copied the object id from the console. Whenever you copy from the console in WebMatrix you're likely to pick up some invisible characters that will cause errors.
In MongoDB Stitch functions it can be done using BSON like below:
Use the ObjectId helper in the BSON utility package for this purpose like in the follwing example:
var id = "5bb9e9f84186b222c8901149";
BSON.ObjectId(id);
For Pythonists:
import pymongo
from bson.objectid import ObjectId
...
for row in collectionName.find(
{"_id" : ObjectId("63ae807ec4270c7a0b0f2c4f")}):
print(row)
To use Objectid method you don't need to import it. It is already on the mongodb object.
var ObjectId = new db.ObjectId('58c85d1b7932a14c7a0a320d');
db.yourCollection.findOne({ _id: ObjectId }, function (err, info) {
console.log(info)
});
Simply do:
db.getCollection('test').find('4ecbe7f9e8c1c9092c000027');
I have a collection with following entry
{
"_id" : "6z2pQDYozQxEyPZYv",
"userId" : "b2dQ6SuPrwmPsLsg8",
"communicatingWith" : [ "KMT74bWPoZxDSKdrx", "KMT74bWPoZxDSKdrx" ]
}
when I query mongo through meteor for the field communicatingWith , if I do a console.log(communicatingWith), the output is
[ 'KMT74bWPoZxDSKdrx', 'KMT74bWPoZxDSKdrx' ].
Even when I do console.log(communicatingWith.length) the output is 2
But when I do
communicatingWith.each(function(item){console.log(item)})
it throws error saying
Exception while invoking method 'createPrivateMsgHanger' TypeError: Object KMT74bWPoZxDSKdrx,KMT74bWPoZxDSKdrx has no method 'each'
Can you please help me understand where things are wrong?
.each is a jQuery function
pure javascript uses Array.forEach(function(item) { //do something here})
I could get around this problem using the following statement
let arr = Array.from(loggedInUserHanger.communicatingWith);
once I have the arr, I can use all Array functions
Another solution would be using forEach. I don't remember seing each in JS before https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach
Looked everywhere online and can't find a simple answer to how to delete an id from MongoDB using MongoHUB.
In MongoHub I click on remove and i get presented with this above the query box:
db.site.markets.remove()
i want to remove this data:
{
"_id": 10,
"item": "box",
"qty": 20
}
Surely this code should work?
db.site.markets.remove(item : 'box' )
or
db.site.markets.remove(_id : 10)
Both of them don't work.
I'm making this too difficult... Stupid though it may sound a right click, delete function would be helpful...
When removing using mongohub you must wrap the parameters in quotes.
{"item" : "box"}
Also when removing by mongodb built in id the ObjectId() function is also required.
{ "_id" : ObjectId( "12345")}
You should give an object to mongodb. And _id column generated by mongodb is type of ObjectId, so you should use ObjectId("10") when passing the parameter as below:
db.site.markets.remove({item : 'box'})
db.site.markets.remove({_id : ObjectId('10')})
I have define 2 reconds in 2 collections separately in one mongo db like this
order:
{
"_id" : ObjectId("53142f58c781abdd1d836fcd"),
"number" : "order1",
"user" : ObjectId("53159bd7d941aba0621073e3")
}
user
{
"_id" : ObjectId("53159bd7d941aba0621073e3"),
"name" : "user1",
"gender" : "male"
}
when I use this command in console, it can not execute
db.orders.find({user: db.user['_id']}) or db.orders.find({user: user['_id']}),
is there anything wrong? Thanks!
Another way is to:
> var user = db.users.findOne({name: 'user1'});
> db.orders.find({user: user._id});
This way can be a bit more flexible especially if you want to return orders for multiple users etc.
Taking your comment:
Thanks, but actually, I want to search all the orders of all users, not only one user. So what would I do? Thanks
db.users.find().forEach(function(doc){
printJson(db.orders.find({user: doc._id}));
});
I think you want:
db.order.find({'user':db.users.findOne({'name':'user1'})._id})
All you need to do is to make a query and check the output before inserting it into the query.
i.e. check that:
db.users.findOne({'name':'user1'})._id
has the output:
ObjectId("53159bd7d941aba0621073e3")
If you want to run larger queries, you're going to have to change your structure. Remember that Mongodb doesn't do joins so you'll need to do create a user document that looks like this:
user
{
"name":"user1",
"gender":"male",
"orders":[
{
'number':'order1'
}
]
}
You can then update this using:
db.user.update({'_id':ObjectId('blah')}, {'orders':{$push:{'number':'order2'}})
This will then start you with order tracking.
Mongo will be able to find using the following:
db.user.find({'orders.numbers':'order2'})
returning the full user record
Maybe you can help this solution:
use orders
db.getCollection('order').find({},{'_id':1})
db.getCollection('user').find({},{'_id':1})
I currently have an ordered JSON string being passed into my iPhone app, which is then being parsed using the JSON Framework.
The data is as follows:
"league_table": object{
"Premiership": array[6],
"Championship": array[6],
"Division 1": array[6],
"Division 2": array[6],
"Division 3": array[6]
}
However when it parses that, it throws out a weird order.
Division 2
Division 1
Championship
"Division 3"
Premiership
Which I got by calling : NSLog(#"%#",[dictionaryValue allKeys]);.
Has anyone experienced this before? Any idea what to do to sort it again?
UPDATE ::
The shortened UN-Parsed JSON is here :
{"league_table":
{
"Premiership":[],
"Championship":[],
"Division 1":[],
"Division 2":[],
"Division 3":[]}
}
As far as I can tell, this is a Key/Value Pair, so it should be parsed in the same order.
For instance going to http://json.parser.online.fr/ and pasting that in will parse it in the correct order.
However the JSON-Framework doesn't parse it the same, it parses it in a strange order with no real sorting going on
JSON object fields don't have a defined order. If you want key/value pairs in a defined order, there are basically two options:
An array of single-field objects:
[{"Premiership": array[6]},
{"Championship": array[6]},
{"Division 1": array[6]},
{"Division 2": array[6]},
{"Division 3": array[6]}]
An array of key/value pairs:
[["Premiership", array[6]],
["Championship", array[6]],
["Division 1", array[6]],
["Division 2", array[6]],
["Division 3", array[6]]]
Sidenote: I'm half-guessing that the relationship between the sample data and JSON. I don't know what object and array[6] are doing there.
Yep, I've seen that before.
Does this cause you a problem? it looks like a Dictionary (keyed) .. so I guess your application just accesses the required elements by it's key.
I believe a JSON array format would maintain the order.
EDIT
Ok, so you need to maintain the order ... but from what you say, it looks like the key isn't important.
Are you in control of the creation of the JSON string ? If so, could you present the data like this :
[
{
"leagueName":"Premiership",
"leagueLines":[...]
},
{
"leagueName":"Championship",
"leagueLines":[...]
},
{
"leagueName":"League One",
"leagueLines":[]
},
... etc ....
]
I've put in the leagueName in just for information ... who know's you might need it for something :)
Good Luck