2013-04-02 10 views
14

私はこのクエリをしました:集計から_idを隠すには?

produits = yield motor.Op(db.users.aggregate, [{"$unwind":"$pup"},{"$match":{"pup.spec.np":nomp}}, {"$group":{"_id":"$pup.spec.id","pup":{"$push":"$pup"}}}]) 

結果は私にこの与える:私は行うことができます

print produits 

{u'ok': 1.0, u'result': [{u'_id': None, u'pup': [{u'avt': {u'fto': ..all the results}}]}]} 

を:

prod = produits["result"] 

[{u'_id': None, u'pup': [{u'avt': {u'fto': ..all the results}}]}] 

が、どのように私は"_id"を隠すんので、私はできるだけで取得する

[{u'pup': [{u'avt': {u'fto': ..all the results}}]}] 

通常のクエリでは、私はちょうど{"_id":0}のようなものを追加します。

答えて

24

あなたは_idを除外するために、結果を予測することができます$ - あなたは何を意味するか、このですか?

http://docs.mongodb.org/manual/reference/aggregation/#pipeline

_idフィールドは常にデフォルトで含まれます。次のように明示的に_idを除外することがあります。

db.article.aggregate(
    { $project : { 
     _id : 0 , 
     title : 1 , 
     author : 1 
    }} 
); 

あなたが一例だから、パイプラインの最初の操作は_idを除外することや、他のはattribsが含まれるであろう。

+0

私は$ project演算子を追加する必要がありますか? –

+0

最後にそれを追加すると、エラーが発生します。 '{{" $ unwind ":" $ pup "}、{" $ match ":{" pup.spec.np ":nomp}}、{" {"$ project":{"_ id":0}} {$ id}:{"$ id": "$ pup"}} ] ' –

+2

あなたのコマンドを見ると、あなたがグループ化しているものがnullであるように見えます。私は構文に慣れていませんが、出力から_idを取り除きたい場合は、パイプライン – sambomartin

2

私はモーターに精通していませんが、あなたは直接結果のdictからプロパティを削除することができるはずです。 MongoDBのドキュメント

から

>>> produits = {u'ok': 1.0, u'result': [{u'_id': None, u'pup': [{u'avt': {u'fto': 'whatever'}}]}]} 
>>> prod = produits['result'] 
>>> del prod[0]['_id'] 
>>> print prod 
[{u'pup': [{u'avt': {u'fto': 'whatever'}}]}] 
+0

はあなたに感謝、はい私はインデックスを使用してPythonを使用してそれを行うことができますが、結果が複数ある場合は複雑になるので、結果(辞書)とリストのインデックスに対して2回反復する必要があります BTW:motorはpymongo、呼び出しをブロックしない呼び出しを行うため、コールバックを使用する点が異なります。 –

-1

これはそれを行うのexaclty mongoWayはありませんが、あなたはこのようにそれを使用すると、すべてを含んでいるオブジェクトを生成するには、このファクトリを使用しますが

/** 
* Factory that returns a $project object that excludes the _id property https://docs.mongodb.com/v3.0/reference/operator/aggregation/project/ 
* @params {String} variable list of properties to be included 
* @return {Object} $project object including all the properties but _id 
*/ 
function includeFactory(/* properties */){ 
    var included = { "_id": 0 }; 
    Array.prototype.slice.call(arguments).forEach(function(include){ 
     included[include] = true 
    }) 

    return { "$project": included } 
} 

_idことができます。

cities.aggregate(
{ "$group": { "_id": null, "max": { "$max": "$age" }, "min": { "$min": "$age" }, "average": { "$avg": "$age" }, "total": { "$sum": "$count" } } }, 
     includeFactory('max','min','average','total') 
) 
+2

ダウンボントは、その理由を説明するコメントが最適です。そうすれば、私たち全員がそのことを知ることができます。 – Danielo515

関連する問題