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');
Related
I'm trying to find all lists which the person number has '-' or '.' inside of it. I already tried this answer, but it's not working for elements inside of the array.
But when I try to find by the entire String, without the regex notation, the document is found.
Per example:
db.getCollection('list').find({"persons.number": "123456789"}) //works!
db.getCollection('list').find({"persons.number": /3/}) //not work...
db.getCollection('list').find({"persons.number": /.*3.*/}) //not work
db.getCollection('list').find({"persons.number": /.*..*/}) //not work
db.getCollection('list').find({"persons.number": /.*[-\.]+.*/}) //not work
If I try to find the document by some attribute outside of the array (an attribute from the list, per example), the /3/, /.*3.*/ and /.*[-\.]+.*/ works.
Document format:
{
"_id" : ObjectId("5af3037ee8006c4a04e84b2f"),
"id" : 1,
"persons" : [
{
"id" : 1,
"number" : "123.123.123-22"
},
{
"id" : 2,
"number" : "123.456.789-11"
}
]
}
So, what are the options?
I'm using the MongoDB from Azure. Executing the db.version() on console returns 3.2.0.
The regex .*[-\.]+.* should work,
Try this,
db.getCollection('list').find({"persons.number": /.*[-\.]+.*/})
For searching multiple patterns , i.e an OR of patterns the regex format is little different.
(pattern1)|(pattern2)
Tried the below mongo query on my local running 3.4.6 , but it should work on 3.2.x as well
db.list.aggregate([{"$unwind":{"path":"$persons"}},{"$project":{"_id":1,"persons.number":1}},{"$match":{"persons.number":{"$regex":/.*(\.)|(\-).*/}}},{"$group":{_id:"$_id"}}])
suppose I have the following datastructure:
var user = {_id: 'foo', age: 35};
var post = {_id: '...', author: {$ref: user, $id: 'foo'},...};
How can I query all posts which references user[foo]? I tried the following but not work:
db.post.find('author._id': 'foo');
var u = db.user.find({_id: 'foo'});
db.post.find('author': u);
neither can I find the answer from the official document and google!
Anyone has any idea?
Got it:
db.post.find({'author.$id': 'foo'})
This db.post.find('author.$id': 'foo') has missing the {}, so the correct sentence is:
db.post.find({'author.$id': 'foo'})
Also this can be achieved with:
db.post.find({'author': DBRef("user", ObjectId('foo'))})
But is more compact and practical the first way.
You can use the .$id reference but it will ignore any indexes on those fields.
I would suggest ignoring that method unless you are querying it directly via the terminal or want to look up something quickly. In using large collections you will want to index the field and query it using the below method.
If you want to use an index query using the following:
db.post.find('author' : { "$ref" : 'user', "$id" : 'foo' , "$db" :'database_name' })
If foo is an object id
db.post.find('author' : { "$ref" : 'user', "$id" : ObjectId('foo') , "$db" :'database_name' })
You can create an index on author by
db.post.ensureIndex( {'author' : 1 } );
For anyone looking for a Java solution to this then if you are using mongojack its really easy:
collection.find(DBQuery.is("user", new DBRef(user.getId(), User.class)));
Where collection is a JacksonDBCollection.
In mongoengine you should just use the instance of the referenced object. It should have the ID set.
Suppose the author is the Author document instance. So using this:
Post.objects(author__eq=author)
you can go through all posts of this author.
Post.author should be defined as ReferenceField
Using Mongo 2.4.1 version
This is how you do it on command line for OLA collection where #DBRef dbrefName
db.OLA.find({"dbrefName.someFieldValue" : "Personal"});
Exact query
db.OLA.find({"dbrefName.$id" : ObjectId("1234")});
I seem to be struggling to find the right way of deleting a document. I.e. should I be using remove() or delete_one() for example and also what is the canonical method of deleting by id, which is a string.
I.e. should I be using the following:
mongo.db.xxx.delete_one({'_id': { "$oid" : str(_id) } })
or can I use another format?
mongo.db.xxx.remove({'_id': { "$oid" : str(_id) } })
mongo.db.xxx.remove({'_id': ObjectId(_id) })
What is the canonical form?
remove is deprecated in the 3.x release of pymongo, so the current canonical form would be to use delete_one:
from bson.objectid import ObjectId
result = mongo.db.xxx.delete_one({'_id': ObjectId(_id)})
The call returns a DeleteResult in which you can inspect the deleted_count field to see if it found a document to delete
You can simply do:
result = mongo.db.xxx.delete_one({})
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')})
My collection structure*"countcollection"* is looks as below
{
"limitcount": 10000,
"currentcount": 100
}
I want to right the mongoquery that able to compare the currentcount<($lt)limitcount
or currentcount>($gt)limitcount.
First, i wrote the mongo query as below
db.countcollection.find({"currentcount":{$lt:{"limitcount"}}});
db.countcollection.find({"currentcount":{$gt:{"limitcount"}}});
but it's failed to execute .
please give your input for this mongoquery.
thanks in advance .
javaamtho.
As Bugai13 said, you can't do a comparison on 2 fields in a query.
The problem with $where is performance - as that is a javascript function that will be executed for every document so it will have to scan through every one.
So, you could store another field (that you could then index) alongside those existing fields
e.g.
{
"limitcount": 10000,
"currentcount": 100,
"remainingcount" : 9900
}
so you could then query on the new field instead:
db.countcollection.find({"remainingcount" : {$gt : 0}})
db.countcollection.find({"remainingcount" : {$lt : 0}})
You can't do what you want using simple query(like you have tried above). There is such bug in mongodb jira and you can vote up for this.
I suppose you shoud use javascript expression like this:
db.countcollection.find( { $where: "this.currentcount < this.limitcount" } );
Hope this help.
$gt:{"limitcount"}}
does not make any sense since you are comparing against the string limitcount. If you want to compare against a pre-defined variable, use the variable but something with quotes around it. Why did you choose this strange syntax?