26

I have a document in MongoDB and I would like to get the ObjectId of this document, but I did not find so far a method that does this to me.

Example of query :

 user= db.users.find({userName:"Andressa"})

This returns this :

 { "_id" : ObjectId("53b1c579bdf3de74f76bdac9"), "userid" : 0, "userName" : "Andressa", "userEmail" : "dessa_beca@hotmail.com", "teams" : [ 1, 2, 3 ] }

I want get the ObjectId to do another query .

Example:

 userID =  `user._id();` //but this does not work, of course, its an example

So, I could user the ObjectId to do another query like this:

 userFind = db.users.find({_id: userID})

UPDATE: This code :

 db.teams.find({_id:{$in: user.teams}})

returns this error:

error: {
    "$err" : "Can't canonicalize query: BadValue $in needs an array",
    "code" : 17287

Does someone know it?

Community
  • 1
  • 1
Andressa Pinheiro
  • 1,517
  • 2
  • 18
  • 28
  • How did you just return an _id field? e.g. I have a method to return objectId field for edit and update user document. Thank heaps! – Stu_Dent Oct 10 '20 at 13:52

8 Answers8

28

In the mongo shell you can use this to retrieve the _id :

user._id.str

or

user._id.toString()

See documentation : http://docs.mongodb.org/manual/reference/method/ObjectId.valueOf/

kranteg
  • 931
  • 1
  • 7
  • 15
11

I got it! Actually , I could do it by this code:

Instead of putting just :

user = db.users.findOne({userName:"And"})

I did just :

  var user = db.users.findOne({userName:"And"})

and

  user._id 

returns the ObjectId("someId") , if I want to keep it in some variable I do:

var Id = user._id. 

About the second question, I dont know.

Andressa Pinheiro
  • 1,517
  • 2
  • 18
  • 28
  • 20
    It's been 3 years, but someone may find it useful: `db.users.find({userName: "And"})[0]._id` – dodo254 Sep 16 '17 at 09:31
3

I ran into what I believe to be the same issue - how to retrieve the ObjectId from an unknown mongo document. I have built a generic datacontext and needed the _id within my update and delete methods. Having found your question while searching for an answer on how to do this, I decided to post what finally worked for me.

private BsonValue GetId<TEntity>(TEntity entity)
{
    var bsonDoc = entity.ToBsonDocument();
    return bsonDoc.GetElement("_id").Value;
}

I then use it something like this:

 var id = GetId<TEntity>(entity);
 var filter = builder.Eq("_id", id);
 var doc = collection.Find(filter).SingleOrDefault();

Hope this helps.

GeekerMode
  • 66
  • 3
2

I think what you are looking for is to get the value of the id:

user= db.users.find({userName:"Andressa"})
.then(data=>return data._id.valueOf())
.catch(err=>console.log(err));
Joshua Bot
  • 21
  • 3
  • 1
    Isn't this basically what [@Kranteg proposed in the top-voted answer](https://stackoverflow.com/a/24558372/3025856)? – Jeremy Caney Jan 06 '22 at 00:35
  • 1
    Checking it now it basically is although it's all about preference: .toString() returns the string with ObjectId in front of it while .valueOf() returns the actual hexadecimal id without any prefixes. – Joshua Bot Jan 07 '22 at 21:28
1

With the MongoDB Node.js drive and with ES6 destructuring

const { _id } = db.collection("users").findOne({ userName:"Andressa" })

Or even better, rename it while restructuring...

const { _id: userId } = db.collection("users").findOne({ userName:"Andressa" })

Then can use userId in your code as needed...

PJately
  • 477
  • 7
  • 7
0

You can use find() method to achieve this.

db.collection.find() method does not return actual document but it return cursor to the document. by iterating through the cursor you will the fields within that document.

Code :

    var cursor=db.collection.find()

    var objectId= cursor.next()._id

above statement get the value of ObjectId from current cursor instance. if you to retrieve all objectId then by iterating through cursor you will get all the values of ObjectId.

To find document directly using objectId received in first step you can use following code snippet:

       db.collection.find( { "_id": objectId},{ fields Of Your Choice } )
DanglingPointer
  • 91
  • 2
  • 13
0

Try this (For Node v12.16.3 / MongoDB MongoDB v4.2.6)

// find if a value exists
collection.find({ "criteria1": value1, "criteria2": value2 }).toArray
(function(err, doc) {

    if (err) {
        console.log('Error, Please Try Again');
    }
    else if (doc.length === 0) {
        console.log('Does Not Exist');
    } else {
        console.log(doc);
        console.log(doc[0]._id)
    }
});
DragonFire
  • 3,722
  • 2
  • 38
  • 51
0

Here I found getting Mongo _Id in my HTTP Response as JSON

Product Entity:

@Document(collection= "Products")
@Data
public class ProductsEntity {

@Field("_id")
private ObjectId _id;
private int index;
private String productId;
private String productName;
private String productDescription;

}

My Product Model :

public class Products {

@Field("_id")
private ObjectId _id;

private int index;
private String productID;
private String productName;
private String productDescription;

}

Here my repository method used with Query , Criteria and MongoOperations.

 @Autowired
 private MongoOperations operations;

 public ProfileEntity findByProductID(String productID){

    Query query = new Query();
    query = Query.query(Criteria.where("productID").is(productID));

    List<ProductEntity> entity = operations.find(query, ProductEntity.class);

    System.out.println(" Profile data from profile collection -- "+ entity);

    return entity.get(0);
 } 

Response of the API :

{
    "productslist": [
        {
            "_id": {
                "timestamp": 1665062474,
                "date": "2022-10-06T13:21:14.000+00:00"
            },
            "index": 4,
            "productID": "4",
            "productName": "Fourth dashboard",
            "productDescription": "This is Fourth dashboard."
        },
        {
            "_id": {
                "timestamp": 1665377430,
                "date": "2022-10-10T04:50:30.000+00:00"
            },
            "index": 5,
            "productID": "5",
            "productName": "Fifth dashboard",
            "productDescription": "This is Fifth dashboard."
        }
    ]
}
Ramya
  • 1
  • 1