英文:
MongoDB filter when two fields equal
问题
{ "history_doc.data.objectId": { "$eq": "_id" } }
{ "history_doc.data.objectId": { "$eq": { "$toString": "_id" } } }
英文:
Does anyone who knows how to filter data and only keep those history_doc.data.objectId equals _id?
I have tried so many methods but none of them works
{'history_doc.data.objectId': {$eq: '$_id'}}
{'history_doc.data.objectId': {$eq: {$toString: '$_id'}}}
答案1
得分: 0
你可以在聚合查询中像这样使用 $expr
和 $eq
与 $toObjectId
:
.aggregate({
$match: {
$expr: {
$eq: [
"_id",
{
"$toObjectId": "$history_doc.data.objectId"
}
]
}
}
})
示例在这里。
英文:
You can use $expr
and $eq
with $toObjectId
into aggregation query like this:
.aggregate({
$match: {
$expr: {
$eq: [
"$_id",
{
"$toObjectId": "$history_doc.data.objectId"
}
]
}
}
})
Example here.
答案2
得分: 0
你可以使用聚合框架来完成:
$match
- 根据自定义条件筛选文档$eq
和$toString
- 用于检查_id
和history_doc.data.objectId
是否相同。
db.collection.aggregate([
{
"$match": {
"$expr": {
"$eq": [
{
"$toString": "$_id"
},
"$history_doc.data.objectId"
]
}
}
}
])
英文:
You can do it with Aggregation Framework:
$match
- to filter documents based on some custom criteria$eq
and$toString
- To check it_id
andhistory_doc.data.objectId
are the same.
db.collection.aggregate([
{
"$match": {
"$expr": {
"$eq": [
{
"$toString": "$_id"
},
"$history_doc.data.objectId"
]
}
}
}
])
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论