powderkeg
powderkeg

Reputation: 361

Get specific part of document

I'm trying Mongo db and I wonder if it's possible to only get a specific part of a document?

For example I have:

{
  "name" : "MongoDB",
  "info" : { x : 203, y : 102 }
}

and I only want the content of info.

The closest I found is db.collection.find({}, { info: 1 }) but this returns me { "info" : { x : 203, y : 102 } } when I only need { x : 203, y : 102 }.

Upvotes: 36

Views: 39865

Answers (6)

Xavier Guihot
Xavier Guihot

Reputation: 61686

  • Starting Mongo 4.2, the $replaceWith aggregation operator can be used to replace a document by another (in our case by a sub-document):

    // { name: "MongoDB", info: { x: 203, y: 102 } }
    db.collection.aggregate({ $replaceWith: "$info" })
    // { "x" : 203, "y" : 102 }
    
  • Prior to Mongo 4.2 and starting Mongo 3.4, $replaceRoot can be used in place of $replaceWith:

    db.collection.aggregate({ $replaceRoot: { newRoot: "$info" } })
    

Upvotes: 1

hecnabae
hecnabae

Reputation: 407

You can use aggregation framework:

  1. $match phase (optional) to filter result.
  2. $project phase to select fields

    db.getCollection('yourCollection').aggregate([ {$match:{_id:ObjectId("566fc97f5b79dff1a73ca2ae")}}, {$project:{_id:0, "x":"$info.x", "y":"$info.y"}} ])

Upvotes: 0

devendra tata
devendra tata

Reputation: 141

MongoDb docs

read this

in this,If you specify no projection, the find() method returns all fields of all documents that match the query.

Upvotes: 0

Alex Gorbunov
Alex Gorbunov

Reputation: 239

You can use distinct() function that resembles by following:

db.collection.distinct("info", {info : {$exists : true}})

Upvotes: 15

Scott Hernandez
Scott Hernandez

Reputation: 7590

No, you cannot return just the values for x/y; even if you limit the fields the outer structure is still returned.

See Result Projections for more info.

Upvotes: 11

Lucas Zamboulis
Lucas Zamboulis

Reputation: 2551

You could do

db.collection.find({},{'info.x':1, 'info.y':1})

but that means listing each and every item of the info object in the projection - which may or may not be what you're looking for.

Upvotes: 29

Related Questions