MongoDB
 SQL >> Base de données >  >> NoSQL >> MongoDB

Utiliser l'opérateur positionnel $ de MongoDB dans une requête profondément imbriquée

Vous obtenez une erreur à cause de

db.users.findOne( { username: 'test', 'kingdoms.buildings.type': 'castle' }, { kingdoms: {$slice: [n, 1]}, 'kingdom.buildings.$': 1 } );

parce qu'il y a une faute d'orthographe (« kingdom.buildings.$ » devrait être « kingdoms.buildings.$ »).
Même ainsi, cette approche ne peut pas accomplir ce que vous attendez.
$ cible toujours kingdoms dans le chemin kingdoms.buildings — le premier tableau.

Voici une approche qui devrait résoudre le problème (V2.6+ requise) :

db.c.aggregate([ { $match : { username : 'test', 'kingdoms.buildings.type' : 'castle' } }, { $project : { _id : 0, kingdoms : 1 } }, { $redact : { $cond : { "if" : { $or : [ { $gt : [ "$kingdoms", [] ] }, { $gt : [ "$buildings", [] ] }, { $eq : [ "$type", "castle" ] } ] }, "then" : "$$DESCEND", "else" : "$$PRUNE" } } } ]).pretty();

Pour ne conserver que le premier élément de kingdoms,

db.c.aggregate([ { $match : { username : 'test', 'kingdoms.buildings.type' : 'castle' } }, { $redact : { $cond : { "if" : { $or : [ { $gt : [ "$kingdoms", [] ] }, { $gt : [ "$buildings", [] ] }, { $eq : [ "$type", "castle" ] } ] }, "then" : "$$DESCEND", "else" : "$$PRUNE" } } }, { $unwind : "$kingdoms" }, { $group : { _id : "$_id", kingdom : { $first : "$kingdoms" } } }, { $group : { _id : "$_id", kingdoms : { $push : "$kingdom" } } }, { $project : { _id : 0, kingdoms : 1 } } ]).pretty();