databasemongodbnosqlmongo-shelldbref

How to acess dbRef.$id and dbRef.$ref in mongosh?


Using MongoDB: 6.0.4 Using Mongosh: 1.4.1

I inserted a book and a publisher (dbRef) with mongosh.

# insert publisher
publisher_id = ObjectId()
db.publishers.insert_one({
    '_id': publisher_id,
    'title': 'XXX',
    'website': 'https://xxxxxxx.com',
})

# insert books
db.books.insert_one({
    'title': 'Good book',
    'author': 'Someone',
    'publishers': [ 
        {
            '$ref': 'publishers',
            '$id': publisher_id, 
        },
    ], 
})

Then run the following commands with mongosh.

> var book = db.books.findOne({title:'Good book'})
> var dbRef = book.publishers[0]
> dbRef
DBRef("publishers", ObjectId("..."))

According to the link below, I think I can access $id and $ref of the dbRef object, but I got empty lines. How can I access $id and $ref with mongosh?

> dbRef.$id 
  // empty line

> dbRef.$ref
  // empty line

> dbRef.collection
publishers

> JSON.stringify(dbRef)
{"$ref":"publishers","$id":"..."}

How to show data from 2 collections in Mongodb with DBRef

UPDATE

For newer version of mongosh,

> dbRef.oid
ObjectId("...")
> dbRef.collection
publishers

For older version of mongosh,

> dbRef.toJSON().$id
ObjectId("...")

> dbRef.toJSON().$ref
publishers

Solution

  • DBRef is a separate data type: https://mongodb.github.io/node-mongodb-native/3.6/api/DBRef.html

    new DBRef(namespace, oid, db)

    Name Type Description
    namespace string the collection name
    oid ObjectID the reference ObjectID
    db string optional db name, if omitted the reference is local to the current db

    Try dbRef.oid