Reputation: 361
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
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
Reputation: 407
You can use aggregation framework:
$project phase to select fields
db.getCollection('yourCollection').aggregate([
{$match:{_id:ObjectId("566fc97f5b79dff1a73ca2ae")}},
{$project:{_id:0, "x":"$info.x", "y":"$info.y"}}
])
Upvotes: 0
Reputation: 141
read this
in this,If you specify no projection, the find() method returns all fields of all documents that match the query.
Upvotes: 0
Reputation: 239
You can use distinct()
function that resembles by following:
db.collection.distinct("info", {info : {$exists : true}})
Upvotes: 15
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
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