Digamos que tengo una colección llamada prueba:
> db.test.find() { "_id" : ObjectId("5887a9202d599801b7df2c3c"), "name" : "soccer66", "ratings" : [ 5, 3.2, 1 ] } { "_id" : ObjectId("5887a9232d599801b7df2c3d"), "name" : "user1", "ratings" : [ 2, 3.2, 1 ] } { "_id" : ObjectId("5887a9262d599801b7df2c3e"), "name" : "user2", "ratings" : [ 2.5, 4.9, 1 ] }¿Cuál es la forma óptima de seleccionar los documentos donde la primera calificación es mayor que la segunda? He intentado muchas consultas. Por el bien de esta publicación, ejecuté lo siguiente nuevamente:
> db.test.aggregate([ {$project:{"isGreater":{$cond:[{$gt:["$ratings.0","$ratings.1"]},true,false]}}}, {$match:{"isGreater": true}}]); > > db.test.find({$where: "this.ratings.0" < "this.ratings.1"});Error: error: { "ok" : 0, "errmsg" : "$where got bad type", "code" : 2, "codeName" : "BadValue" }db.test.find({"valoraciones.0": {"$gt": "valoraciones.1"}});
Prueba de que estoy usando el índice de matriz correcto con ratings.#:
> db.test.find({"ratings.0":5}); { "_id" : ObjectId("5887a9202d599801b7df2c3c"), "name" : "soccer66", "ratings" : [ 5, 3.2, 1 ] } >En su instrucción $where , todo el predicado "where" debe estar entre comillas:
db.test.find({$where: "this.ratings[0] < this.ratings[1]"});$where .Debe usar el marco de agregación para esto.
db.test.aggregate([ { "$match": { "ratings.1": { "$exists": true } } }, { "$redact": { "$cond": [ { "$gt": [ { "$arrayElemAt": [ "$ratings", 0 ] }, { "$arrayElemAt": [ "$ratings", 1 ] } ]}, "$$KEEP", "$$PRUNE" ] }} ])