[mongodb] how do I query whether there is a pid whose value is equal to the _ id field?

the data format is as follows:

/*  */
{
    "_id" : ObjectId("5c1f795fbb0eb4399f554e08"),
    "pid" : ObjectId("5c10cf1acd6ff5730f265a8a"), //_id
    "know" : ""
},

/*  */
{
    "_id" : ObjectId("5c10cf1acd6ff5730f265a8a"),
    "know" : ""
},

I want to query all parents first and return a hasChild field. If there is a subset pid equal to the parent set _ id , then return true , otherwise return false

as above, the result returned by the query parent set should be as follows:

{
    "_id" : ObjectId("5c10cf1acd6ff5730f265a8a"),
    "know" : "",
    "hasChild": true
}

hope to use Aggregation to solve the problem, rather than cycle, ask God for advice!

Mar.11,2022

refer to $lookup (aggregation)

.

I hope it will be helpful to you


it is possible to do this. Use $expr (MongoDB > = 3.6):

db.bar.find({$expr: {$eq: ["$_id", "$pid"]}})

but this is not recommended. Because this query cannot use the index, it can only do a full table scan to complete the task, which is quite inefficient.
it is also recommended that you modify the data model and not use pid=_id to judge the parent node, but use pid=0, or add another tag root=true and so on. You can add the corresponding index to speed up the query.
moreover, semantically speaking, it doesn't make sense that pid equals itself.

MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1b3bd9f-2c2c2.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1b3bd9f-2c2c2.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?