使用 Mongo shell,我尝试添加一个与集合中所有文档的现有字段具有相同值的字段。假设我们有两个文档:
{
'foo': 'str1'
}
Run Code Online (Sandbox Code Playgroud)
和
{
'foo': 'str2'
}
Run Code Online (Sandbox Code Playgroud)
我想插入一个新字段'foo_new',其值分别为'foo',以便文档成为
{
'foo': 'str1'
'foo_new': 'str1'
}
Run Code Online (Sandbox Code Playgroud)
和
{
'foo': 'str2'
'foo_new': 'str2'
}
Run Code Online (Sandbox Code Playgroud)
我用来在 Mongo shell 中更新集合(例如“coll”)的命令是
db.coll.update({}, {$set: {'foo_new': '$foo'}}, {multi: true})
Run Code Online (Sandbox Code Playgroud)
运行该命令的结果是两个更新的文档
{
'foo': 'str1'
'foo_new': '$foo'
}
Run Code Online (Sandbox Code Playgroud)
和
{
'foo': 'str2'
'foo_new': '$foo'
}
Run Code Online (Sandbox Code Playgroud)
ie'$foo'由于某种原因被解释为文字。
我试图在 jq 中对数组进行切片,其中结束索引作为来自 shell (bash) 的参数传递:
end_index=7
cat obj.json | jq --arg eidx $end_index, '.arr[0:$eidx]'
Run Code Online (Sandbox Code Playgroud)
当索引被硬编码时,这会按预期工作
cat obj.json | jq '.arr[0:7]'
Run Code Online (Sandbox Code Playgroud)
但在顶部的示例中,我收到一条错误消息
jq: error (at <stdin>:0): Start and end indices of an array slice must be numbers
Run Code Online (Sandbox Code Playgroud)
我怀疑这可能与 jq 如何处理切片运算符中的变量替换有关[:],但我解决该问题的尝试(例如通过将变量名称括在大括号中.arr[0:${eidx}])都没有奏效。
我有一个JSON对象数组,jsonArr说,有以下几种:
[
{ "attr1" : "somevalue",
"attr2" : "someothervalue"
},
{ "attr1" : "yetanothervalue",
"attr2" : "andsoon"
},
...
]
Run Code Online (Sandbox Code Playgroud)
使用jsoncpp,我试图遍历数组并检查每个对象是否有成员"attr1",在这种情况下我想将相应的值存储在向量中values.
我尝试过类似的东西
Json::Value root;
Json::Reader reader;
Json::FastWriter fastWriter;
reader.parse(jsonArr, root);
std::vector<std::string> values;
for (Json::Value::iterator it=root.begin(); it!=root.end(); ++it) {
if (it->isMember(std::string("attr1"))) {
values.push_back(fastWriter.write((*it)["uuid"]));
}
}
Run Code Online (Sandbox Code Playgroud)
但不断收到错误消息
libc++abi.dylib: terminating with uncaught exception of type Json::LogicError: in Json::Value::find(key, end, found): requires objectValue or nullValue
Run Code Online (Sandbox Code Playgroud)