I'm trying Mo开发者_开发问答ngo 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 }
.
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.
You can use distinct()
function that resembles by following:
db.collection.distinct("info", {info : {$exists : true}})
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.
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 startingMongo 3.4
,$replaceRoot
can be used in place of$replaceWith
:db.collection.aggregate({ $replaceRoot: { newRoot: "$info" } })
MongoDb docs
read this
in this,If you specify no projection, the find() method returns all fields of all documents that match the query.
You can use aggregation framework:
- $match phase (optional) to filter result.
$project phase to select fields
db.getCollection('yourCollection').aggregate([ {$match:{_id:ObjectId("566fc97f5b79dff1a73ca2ae")}}, {$project:{_id:0, "x":"$info.x", "y":"$info.y"}} ])
精彩评论