Home > Software design >  Is there an equivalent of WITH from CYPHER (neo4j) in MQL (MongoDB Query Language)?
Is there an equivalent of WITH from CYPHER (neo4j) in MQL (MongoDB Query Language)?

Time:08-18

Is it possible in MongoDB to pass several variables in one query and use several database searches?

Example in Neo4j - finding the first person, and then finding results based on the first search:

MATCH (n {name: 'Anders'})--(m)
WITH m
ORDER BY m.name DESC
LIMIT 1
MATCH (m)--(o)
RETURN o.name

Is it possible to get something similar in MongoDB?

At the moment I have an idea only to make two separate queries. If this is the only solution, how should it be done to optimally transfer this data between queries? I am using the mongodb driver on nodejs.

CodePudding user response:

This is a sample where you use MongoDb which is similar to Neo4j find the first node. Then using that node to find another node related to the first node.

//create sample data
use test1
db.employees.insertMany([
  {empId: 1, name: 'Anders', related: 'Dave' },
  {empId: 2, name: 'Dave', related: 'Mark' }
]); 

// this is similar to find Anders and sort the result in descending order (-1) and return the related person Dave
temp = db.employees.find({"name": "Anders"}).sort({ "name": -1 }).limit(1).map(function(el) { return el.related } );
// then search the name Dave based on the previous find
db.employees.find({"name": {$in: temp}})

Result:
{ "_id" : ObjectId("62fc509b4f1f4a75855bccec"), "empId" : 2, "name" : "Dave", "related" : "Mark" }
  • Related