如何投影字段是否存在 [英] How to project whether field exists
问题描述
如果我有类似以下结构的文档.我正在用计算结果更新它们,我想知道结果是否已经插入到文档中.假设我对每个文档运行计算c"和计算d".现在我想显示一个包含所有文档的表格,并显示是否已经执行了计算d".对于这张表,我不关心计算c".
If I have documents with similar structure as below. I am updating them with the results of the computations and I want to know whether the result has already been inserted into a document or not. Let's say for each document I run computation 'c' and computation 'd'. Now I want to display a table of all documents and show whether a computation 'd' has been already carried out. And for this table I do not care about computation 'c'.
{
"_id":1
"a":1,
"resultsOfComputation":{
"c":{large embedded document},
"d":{large embedded document}
}
}
{
"_id":2
"a":1,
"resultsOfComputation":{
"c":{large embedded document}
}
}
我想得到一个结果,告诉我文档是否包含特定字段.例如,我想知道它是否包含字段resultsOfComputation.d",无论该字段的值是什么.
I would like to get a result that tells me whether a document contains a specific field. For example, I would like to know whether it contains field "resultsOfComputation.d", no matter what is the value of that field.
resultsOfComputation.d"的查询结果示例如下:
An example of the result of the query for "resultsOfComputation.d" would be:
{
"_id":1
"a":1,
"resultsOfComputation":{
"d":true
}
}
{
"_id":2
"resultsOfComputation":{
"d":false
}
}
如果resultsOfComputation.d"不在文档中,它也可以是未定义的,这也可以:
If "resultsOfComputation.d" is not in the document it can also be undefined, which is also ok:
{
"_id":1
"a":1,
"resultsOfComputation":{
"d":true
}
}
{
"_id":2
"a":1,
"resultsOfComputation":{}
}
一般来说,这个想法是获取文档的所有根元素,但对于选定的(一个)计算结果只获取 true/false/undefined,因为计算结果是一个大型嵌入文档.
In general, the idea is to get all the root elements of the documents, but only true/false/undefined for the selected (one) result of computation, since the result of computation is a large embedded document.
推荐答案
运行以下聚合管道以获得所需的结果:
Run the following aggregation pipeline to get the desired results:
db.collection.aggregate([
{
"$project": {
"a": 1,
"resultsOfComputation": {
"d": { "$gt": ["$resultsOfComputation.d", null] }
}
}
}
])
样本输出
/* 1 */
{
"_id" : 1,
"a" : 1,
"resultsOfComputation" : {
"d" : true
}
}
/* 2 */
{
"_id" : 2,
"a" : 1,
"resultsOfComputation" : {
"d" : false
}
}
这篇关于如何投影字段是否存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!