我有这个简单的更新api调用: 这是我的文件:
{
"_id" : ObjectId("577a5b9a89xxx32a1"),
"oid" : {
"a" : 0,
"b" : 0,
"c" : NumberLong("1260351143035")
},
"sessions" : [
{
}
]
}
然后我尝试在会话数组中插入1个元素:
db.getCollection('CustomerInfo').update({"oid.c":1260351143035},{$push:{"sessions.$.asessionID":"test123"}})
但我得到了这个错误:
WriteResult({
"nMatched" : 0,
"nUpserted" : 0,
"nModified" : 0,
"writeError" : {
"code" : 16837,
"errmsg" : "The positional operator did not find the match needed from the query. Unexpanded update: sessions.$.asessionID"
}
})
使用$ set即可获得相同的错误
答案 0 :(得分:4)
如错误所示,
"位置操作员未找到查询所需的匹配项。 未更新的更新:会话。$。asessionID",
如果the array to be updated is also part of the query,位置运算符将起作用。在您的情况下,查询仅涉及嵌入的文档oid
。在您的情况下使用的最佳更新运算符是 $set
。
您可以在查询中包含sessions数组,例如:
db.getCollection('CustomerInfo').update(
{
"oid.c": 1260351143035,
"sessions.0": {} // query where sessions array first element is an empty document
/* "sessions.0": { "$exists": true } // query where sessions array first element exists */
},
{
"$set": { "sessions.$.asessionID": "test123" }
}
)
答案 1 :(得分:0)
正如 documentation 所说,您可以执行以下操作:
#toy df
set.seed(1)
df <- data.table(
date = rep(seq(as.Date("2020-01-01"),as.Date("2020-01-05"),by="day"),each=6),
k = rep(c("A.mean","A.median","A.min","B.mean","B.median","B.min"),5),
v = runif(30,0,50)
) %>%
pivot_wider(names_from = k, values_from = v)
df %>% head
date A.mean A.median A.min B.mean B.median B.min
<date> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1 2020-01-01 13.3 18.6 28.6 45.4 10.1 44.9
2 2020-01-02 47.2 33.0 31.5 3.09 10.3 8.83
3 2020-01-03 34.4 19.2 38.5 24.9 35.9 49.6
4 2020-01-04 19.0 38.9 46.7 10.6 32.6 6.28
5 2020-01-05 13.4 19.3 0.670 19.1 43.5 17.0
#pivot longer by group prefix
df %>%
select(date,matches("A\\.")) %>%
rename_with(~str_replace(.x,"A\\.","")) %>%
mutate( k = "A") %>%
bind_rows(
df %>%
select(date,matches("B\\.")) %>%
rename_with(~str_replace(.x,"B\\.","")) %>%
mutate( k = "B")
)
date mean median min k
<date> <dbl> <dbl> <dbl> <chr>
1 2020-01-01 13.3 18.6 28.6 A
2 2020-01-02 47.2 33.0 31.5 A
3 2020-01-03 34.4 19.2 38.5 A
4 2020-01-04 19.0 38.9 46.7 A
5 2020-01-05 13.4 19.3 0.670 A
6 2020-01-01 45.4 10.1 44.9 B
7 2020-01-02 3.09 10.3 8.83 B
8 2020-01-03 24.9 35.9 49.6 B
9 2020-01-04 10.6 32.6 6.28 B
10 2020-01-05 19.1 43.5 17.0 B